Q
Q
Quad_Tree2019-07-05 22:44:28
Hibernate
Quad_Tree, 2019-07-05 22:44:28

How to implement OneToMany communication?

I have a product class:

@Entity
public class Product {

    set<Category> categories;
}

And I need to link it somehow to the category
@Entity
public class Category {
   //...
}

However, when deleting a product, the categories associated with it should not be deleted. And vice versa. When deleting a category, products should remain in the database, and Set should immediately be updated (become one category less). How to implement it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Talaiko, 2019-07-16
@jsdevel

@Table(name="parent")
class Parent {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
 
    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
    private Set<Child> attachments = new HashSet<Child>();
    .....
}
 
@Entity
@Table(name="child)
class Child {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
 
    @ManyToOne
    @JoinColumn(name = "parent_id", nullable = false)
    private Parent parent;
    ...
}
@Entity

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question