The Most Efficient Data Type For Your Association
The Most Efficient Data Type For Your Association
@Entity
public class Book {
@ManyToMany
@JoinTable(name = "book_author",
joinColumns = { @JoinColumn(name = "fk_book") },
inverseJoinColumns = { @JoinColumn(name = "fk_author") })
private Set authors = new HashSet();
...
}
www.thoughts-on-java.org
Best Practices for Many-to-Many Associations
2. Why you need utility methods to manage your
association
Bidirectional associations are mapped to an entity attribute on both
ends of the relationships. If you add or remove an association, you
always need to perform the change on both ends of the association.
Utility methods your entities make updating and removing much easier.
Within this methods, you perform the required operations on both
entities.
@Entity
public class Author {
@ManyToMany(mappedBy = "authors")
private List<Book> books = new ArrayList<Book>();
...
www.thoughts-on-java.org
Best Practices for Many-to-Many Associations
3. The right FetchType for an efficient mapping
You should always use FetchType.LAZY for your many-to-many
associations. It tells your persistence provider not to fetch the
associated entities from the database until you use them. That’s
usually the case when you call its getter method for the first time.
Luckily, that’s the default for all to-many associations. So, please
make sure that you don’t change it.
Author a = em.createQuery(
"SELECT a FROM Author a JOIN FETCH a.books “
+ “WHERE a.id = 1", Author.class).getSingleResult();
It not only gets translated into a SQL JOIN, as it’s the case for a JPQL
JOIN clause, it also forces your persistence provider to extend the
SELECT clause by all columns that are mapped by the associated
entity.
www.thoughts-on-java.org