How to create a reverse connection for a unidirectional relationship?

I think itโ€™s easy, but I canโ€™t figure it out.

If I have Foo and Bar entities:

@Entity class Foo{ @OneToMany List<Bar> bars; } @Entity class Bar{ @Column int data; } 

and if I want to create a Join object ( javax.persistence.criteria.Join<Foo, Bar> ), I can do it like this:

 Root<Foo> root = ...; Join<Foo,Bar> join = root.join(Foo_.bars); 

But how can I do the reverse connection

 Join<Bar,Foo> inverseJoin = barRoot.join....()...? 

since I don't have a java field in the Bar class that points to its parent name Foo, is this a one-way relation?

+6
source share
1 answer

If you need a famous bar, which is its affiliation, this will be appropriate. The sentence will not be translated into SQL JOIN, but it is semantically equivalent.

 CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<Foo> cq = cb.createQuery(Foo.class); Root<Foo> fooRoot = cq.from(Foo.class); Root<Bar> barRoot = cq.from(Bar.class); cq.select(fooRoot); cq.where(barRoot.in(fooRoot.get("bars"))); 
0
source

Source: https://habr.com/ru/post/977657/


All Articles