简体   繁体   中英

Is there any approach to make Join with JPA2 criteria API like this?

I'm in trouble with JPA2 criteria API. Is there any approach to make smth like this with JPA2 criteria API:

SELECT t1.id FROM Table1 t1 INNER JOIN Table2 t2 ON (t1.id = t2.id)

With these rules:

  1. table1 hasn't table2 reference
  2. table2 has table1 reference
  3. the result should be table1 ids

I'm consfused with JPA2 criteria API Root. How to create join in this situation? Should I use two ROOT's : one for JOIN, another for SELECT? please response

The JPQL query would simply be

select e1.id from Entity2 e2 join e2.entity1 e1

With the criteria API, it would look like this (untested. I hate this API):

CriteriaQuery<String> cq = cb.createQuery(Long.class);
Root<Entity2> e2 = cq.from(Entity2.class);
cq.select(e2.get(Entity2_.entity1).get(Entity1_.id));

Using where You could do a usual JPQL cross-product join:

SELECT t1.id FROM Table1 t1, Table2 t2 WHERE t2.t1_id = t1.id

JPA support for right joins JPA does not support right join queries. From here :

Right outer joins and right outer fetch joins are not required to be supported in Java Persistence 2.0. Applications that use RIGHT join types will not be portable.

Native SQL query So another option would be using a native SQL query.

SELECT Table1.id FROM Table1, Table2 WHERE Table2.t1_id = Table1.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM