I have the following tables:
[ table : column1, column2 ]
A : id, name
B : id, name
AB : idA, idB
AB is a join table.
Then I have this method on hibernate class B
@OneToMany( fetch = FetchType.EAGER)
@JoinTable( name = "AB",
joinColumns = @JoinColumn( name = "idB"),
inverseJoinColumns = @JoinColumn( name = "idA") )
public List<A> getAs(){
//return the list of matching stuff
}
This works perfectly fine.
Now I want to do this sql query in hibernate:
select * from B inner join AB on B.id = AB.idB where AB.idA = 1234
Essentially, ‘list me all B’s that reference A with id 1234’
I could do straight sql, but that would defeat the purpose of getAs()
Is it possible to construct a Criterion/Restriction clause to achieve this?
Relationship between
AandBis not one-to-many in this case, but rather many-to-many. You should map it as such:Note that eagerly fetching a collection is not a good idea in most cases, hence
fetch = FetchType.EAGERremoved above. You can now do the same onAside to make relationship bidirectional:Now getting all
Bs for givenAis just a matter of callinggetBs()on thatAinstance. You can create criteria / write HQL to do that as well – from either side.