could someone tell me if this is the right way to do bidirectional mapping?
class User {
@OneToMany(cascade=CascadeType.ALL, mappedBy="user")
private List<item> items;
}
class Item {
@ManyToOne
private User user;
}
Now, if I delte an Item, I do not want the user to be deleted.
If I delete a User, I want its associated item to be deleted, because it is unique to the user.
And another question: if I create an Item, I do:
User user = new User();
Item item = new Item();
user.getItems().add(item);
item.setUser(user);
persist(item);
Do I have to both set the item to the user, and the user vice versa to the item?
ty
Yes, your relationship/mapping has been annotated correctly. Deleting an
Itemwill not delete its associatedUser. Deleting aUserwill delete everyItemassociated with that user.You don’t need to bidirectionally link them yourself (although there is no harm in doing so), at least not in terms of getting the correct information stored in the database. Note that as database operations cascade from the
Userto theItem(and not vice-versa) you will probably want to callpersist(user)instead ofpersist(item). This will automatically persistitem, as long as you add it to the list inuser.