0

How to write a JPA query that make a join between 2 entities

EntityA

@Id

long id

String field1 String field2

EntityB

@Id

String field1

@Id

String field2

How can I write a join like This in JPQL

select * from entityA,entityB where entityB.field1 = entityA.field1
and entityB.field2 = entityA.field2
Suhaib Janjua
  • 3,538
  • 16
  • 59
  • 73
Shrikant Gupta
  • 127
  • 1
  • 1
  • 9

2 Answers2

1

If you could change your code to include reference to EntityB in EntityA you can use this:

CriteriaQuery<EntityA> cq = cb.createQuery(EntityA.class);
Root<EntityA> root = cq.from(EntityA.class);
Join<EntityA, EntityB> join = root.join(EntityA_.entityBs);
Sim
  • 482
  • 4
  • 9
0

Inner join:

select * from entityA inner join entityB on entityA.field1 = entityB.field2

Left outer join:

select * from entityA left outer join entityB on entityA.field1 = entityB.field2

Change entities and use left join again instead of right join:

select * from entityB left outer join entityA on entityA.field1 = entityB.field2

Useful posts: http://chrisiecorner.blogspot.com/2012/12/jpa-and-outer-joins.html, RIGHT JOIN in JPQL

So better way is criterion query, see: Querying Relationships Using Joins

Community
  • 1
  • 1
AppLend
  • 1,644
  • 1
  • 15
  • 12