kfc
kfc

Reputation: 313

how to left join two unrelated entities with JPA criteria api?

using JPA 2.1 and hibernate 5.1.x, this is possible with JPQL

select s.lowerBound,
l.status
...
from Serie s
left join Line l on
s.lowerBound between l.lineStart and l.lineEnd

how do i write this using Criteria api? i attempted this

Root<Serie> serieRoot = query.from(Serie.class);
Root<Line> lineRoot query.from(Line.class);
query.where(criteriaBuilder.between(s.get("lowerBound"), l.get("lineStart"), s.get("lineEnd")))

but this doesn't allow me to specify it's a left join.

Upvotes: 7

Views: 4945

Answers (1)

ytg
ytg

Reputation: 1857

What you do with your Criteria query doesn't allow you to specify that as a left join, because it's not really a left join. You just have multiple roots in your query, and according to the Hibernate documentation that uses cartesian products, however with a left join you get nulls on the right side if there are no matches.

Since the Form interface only allows you to create joins from attributes of your entity, I think what you want to achieve is not doable with the Criteria API. You either have to do two queries to the database or you have to use JPQL or SQL to do it in one query.

Upvotes: 5

Related Questions