我有两个实体,公司:
@Entity
@Table(name = "companies")
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "company_id")
private List<CompanyRelation> companyRelations;
private String name;
@OneToOne(cascade = CascadeType.ALL)
private Address address;
和CompanyRelation:
@Entity
@Table(name = "company_relations")
public class CompanyRelation {
@Id
@GeneratedValue
private Long id;
@OneToOne
private Company relatedCompany;
如何构建hql查询以使用companyId和relatedCompanyId获取CompanyRelation?这样的事情:
CompanyRelation findByCompanyIds(Long companyId, Long relatedCompanyId);
答案 0 :(得分:1)
首先让我从这个建议开始。 Based on this article我建议您将 @OneToMany关联双向映射,如下所示:
@Entity
@Table(name = "companies")
public class Company {
//..
@OneToMany(mappedBy = "relatedCompany", cascade = CascadeType.ALL)
private List<CompanyRelation> companyRelations = new ArrayList<>();
//..
}
@Entity
@Table(name = "company_relations")
public class CompanyRelation {
//..
@ManyToOne
@JoinColumn(name = "company_id")
private Company relatedCompany;
//..
}
基本上让 ToMany 一侧拥有数据库中的关联(company_relations表上的company_id外键列)
考虑到这一点,您可以使用以下JPQL基于公司ID获取CompanyRelation:
List<CompanyRelation> companyRelations = entityManager.createQuery(
"select cr from CompanyRelation cr where cr.relatedCompany.id = :companyId", CompanyRelation.class)
.setParameter("companyId", myCompanyId).getResultList();