Hello Hibernate/JPA gurus!
I am new to Hibernate, and have a question.
Say I have a bidirection relationship between Books and Tags (any book can be tagged with any tag)
Code:
Tables:
book (bookid, bookname)
tag (tagid, tagname)
booktaglink (booktaglinkid, bookid, tagid)
public class Book() {
@ManyToMany(fetch = FetchType.LAZY)
@Cascade({CascadeType.MERGE, CascadeType.PERSIST, CascadeType.EVICT})
@JoinTable(name = "booktaglink",
joinColumns = {@JoinColumn(name = "bookid") },
inverseJoinColumns = {@JoinColumn(name = "tagid") })
private List<Tag> tags = new ArrayList()
}
public class Tag() {
@ManyToMany(fetch = FetchType.LAZY, mappedBy="tags")
@Cascade({CascadeType.MERGE, CascadeType.PERSIST, CascadeType.EVICT})
private List<Book> books = new ArrayList()
}
So, above... I have Books and Tags bidirectional relationship, so I can retrieve tags that are associated with the book, and books that are associated with the tags. However, Books owns the relationship.
1. Say I want to delete a tag. Is this correct?
Code:
Tag tagToDelete;
List<Book> books = tag.getBooks()
for (Book book: books) {
book.getTags().remove(tagToDelete);
dataSource.save(book)
}
dataSource.delete(tagToDelete);
1. Why do I have to open the owner of association (in this case Book class) and remove the tag I am trying to delete? Can I simply cascade the delete and remove all associations with books? This sucks because if I simply do dataSource.delete(tagToDelete), it will leave all the associations in the link table, and cause errors. Is there any way to automate the delete process instead of looping as I did in the example above.
2. Is there a general rule about who should own the relationship?
3. Why would anyone create a uni-directional relationship? If this was unidirectional, and I am trying to delete a tag, I will never be able to delete the associations except if I loop through all the books in the database and remove the tag I am deleting. Seems inefficient.
Thanks so much!!
PA