如何编写在2个实体之间进行连接的JPA查询
EntityA
@Id
long id
String field1 String field2
EntityB
@Id
String field1
@Id
String field2
如何在JPQL
中编写类似于此的连接select * from entityA,entityB where entityB.field1 = entityA.field1
and entityB.field2 = entityA.field2
答案 0 :(得分:1)
如果您可以更改代码以在EntityA中包含对EntityB的引用,您可以使用:
CriteriaQuery<EntityA> cq = cb.createQuery(EntityA.class);
Root<EntityA> root = cq.from(EntityA.class);
Join<EntityA, EntityB> join = root.join(EntityA_.entityBs);
答案 1 :(得分:0)
内部联接:
select * from entityA inner join entityB on entityA.field1 = entityB.field2
左外连接:
select * from entityA left outer join entityB on entityA.field1 = entityB.field2
更改实体并再次使用左连接而不是右连接:
select * from entityB left outer join entityA on entityA.field1 = entityB.field2
有用的帖子:http://chrisiecorner.blogspot.com/2012/12/jpa-and-outer-joins.html,RIGHT JOIN in JPQL
更好的方法是标准查询,请参阅:Querying Relationships Using Joins