Fetching Nested collections in JPA


While coding in JPA with hibernate underneath I got an exception org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags. I was using “LIST” for the association and fetching eagerly

	@ManyToMany(cascade={CascadeType.MERGE,CascadeType.REFRESH},fetch = FetchType.EAGER)
	@JoinTable(name="class_subject", 
	joinColumns={@JoinColumn(name="classid")}, inverseJoinColumns=@JoinColumn(name="subjectid"))
	private List<SubjectDetails> subjects;

The problem seems to be two fold:

  1. JPA allows only two level of nesting for collection, Parententity->Childentity is fine but it does not allow Parententity->childentity->SubChildEntity
  2. Using List for collection instead of SET -remember a SET guarantees unique elements while list does not

What could be solution:

  1. Use SET instead of List and thats what I have done for the moment
	private SET<SubjectDetails> subjects;

  • Hibernate does allow, so we can use specific annotation but it will defy the whole purpose of using JPA
  • Review the model, instead of depending on Object graph to be fetched “Automagically” by ORM, can we move the logic in service layer and do the population as on need basis for required UI? And if you say it would throw lazy initialization because you have used session at DAO -Red Flag -its an anti pattern
  • About these ads

    About ChandanPandey

    Try to come up with a good design as by product of good coding practices

    Posted on December 22, 2012, in Hibernate, Java and tagged , , . Bookmark the permalink. Leave a comment.

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s

    Follow

    Get every new post delivered to your Inbox.

    Join 32 other followers

    %d bloggers like this: