13

I'm having some issues getting a bidirectional one-to-many association working with JoinTables. This is what I got:

Class A:

@OneToMany
@JoinTable(name="join_table", 
    JoinColumns={@JoinColumn(name="a_id")},
    inverseJoinColumns={@JoinColumn(name="b_id")}
)
@Cascade(org.hibernate.annotations.CascadeType.ALL)
public Set<B> getBs() {
    return bs;
}

Class B:

@ManyToOne
@JoinTable(name="join_table", 
    joinColumns={@JoinColumn(name="b_id", insertable=false,updatable=false)},
    inverseJoinColumns={@JoinColumn(name="a_id", insertable=false,updatable=false)})
public A getA() {
    return a;
}

If I create a instance of A and B, add the instance of B to A and save. It works. But when I reload the instance of A and try and access the set of Bs it throws a LazyInitializationError with the message "illegal access to loading collection ".

Where am I going wrong here? :) Can anybody point me to a example of bidirectional association which uses a join table. And where the ownership is kept to Class A, I have searched though the documentation at hibernate.org but I cant seem to find it.

-Daniel

JustDanyul
  • 13,294
  • 7
  • 48
  • 68

1 Answers1

7

Your mapping are proper and that's why the entry is getting saved in the Database. The issue in fetching is because of the Lazy Initialization.

To solve it modify mapping of the class A as,

@OneToMany(fetch=FetchType.LAZY)
@JoinTable(name="join_table", 
    joinColumns={@JoinColumn(name="a_id")},
    inverseJoinColumns={@JoinColumn(name="b_id")}
)
@Cascade(org.hibernate.annotations.CascadeType.ALL)
public Set<B> getBs() {
    return bs;
} 

This will fire an additional query to the table B and initialize the collection. It might affect the performance depending on the no of entries in your defendant table.

Read the API here for more information.

Community
  • 1
  • 1
ManuPK
  • 10,995
  • 9
  • 54
  • 75