简体   繁体   中英

JPA - Writing join query with 2 foreign keys

I have 2 entities:

@Entity
@Table(name = "HOUSE")
public class House {
  //other fields
  @ManyToOne
  @JoinColumn(name = "OWNER_1", referencedColumnName = "OWNER_ID")
  private Owner owner1;

  @ManyToOne
  @JoinColumn(name = "OWNER_2", referencedColumnName = "OWNER_ID")
  private Owner owner2;
}

@Entity
@Table(name = "OWNER")
public class Owner {
  @Id
  @Column(name = "OWNER_ID")
  private String id;
}

I have the SQL query like this to join 2 tables:

select a.*, b.* from HOUSE a INNER JOIN OWNER b on a.OWNER_1 = b.OWNER_ID or a.OWNER_2 = b.OWNER_ID

But I don't know how to write it in JPA query. Anyone can help?

JPA query would be quite similar:

select a, b 
from House a, Owner b 
where a.owner1.id= b.id or a.owner2.id = b.id

Just keep in mind that the result of query would be a List<Object[2]> , which you have to parse yourself.

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