I am using JPA 2.0
and Spring
in my development. My entity class contains two @ManyToMany
relationships.
@Entity(\"
The best way is to make the XxxtoMany associations lazy (the default). This way, the collections will only be loaded when needed, or when you tell Hibernate to fetch them eagerly using a query with a join fetch clause. Making them EAGER forces Hibernate to always load them, even when you don't need them.
Of course, if you need them and they are configured as LAZY, they can only be loaded if the session is still open. Once the session is closed, the entity becomes detached, and the collections can't be lazy-loaded anymore. You thus need to initialize them explicitly (by calling a method of the collection, or by invoking Hibernate.initialize(collection)
) before closing the session.
If you really want to keep them eagerly loaded, then only one of them should be a bag (i.e. of type Collection
or List
). The others should be declared as Set
.
Side note: the mapping of the second association is wrong: you're using the same join column twice.
To avoid the MultipleBagFetchException
, instead of using FetchType.EAGER
, try using the @LazyCollection(LazyCollectionOption.FALSE)
as in this example:
@ManyToMany
@LazyCollection(LazyCollectionOption.FALSE)
@JoinTable(name = "payitem_m_assig", joinColumns = @JoinColumn(name = "pay_item_id", nullable = e), inverseJoinColumns = @JoinColumn(name = "minor_pay_item_id", nullable = false))
public Collection<MinorPayItemData> getMinorPaymentItem()
{
return minorPaymentItem;
}
Here is a small description of from the docs:
@LazyCollection: defines the lazyness option on @ManyToMany and @OneToMany associations. LazyCollectionOption can be TRUE (the collection is lazy and will be loaded when its state is accessed), EXTRA (the collection is lazy and all operations will try to avoid the collection loading, this is especially useful for huge collections when loading all the elements is not necessary) and FALSE (association not lazy)
@Fetch: defines the fetching strategy used to load the association. FetchMode can be SELECT (a select is triggered when the association needs to be loaded), SUBSELECT (only available for collections, use a subselect strategy - please refers to the Hibernate Reference Documentation for more information) or JOIN (use a SQL JOIN to load the association while loading the owner entity). JOIN overrides any lazy attribute (an association loaded through a JOIN strategy cannot be lazy).
I hope it helps