学习如何编写 JPA 查询。请告诉我是否可以更有效地编写以下查询,可能在单个选择语句中。可能是加入,但不知道如何去做。
class Relationship {
@ManyToOne
public String relationshipType; //can be MANAGER, CUSTOMER etc
@ManyToOne
public Party partyFrom; // a person who has a relation
@ManyToOne
public Party partyTo; // a group a person relate to
}
查询:
String sql = "";
sql = "select rel.partyTo";
sql += " from Relationship rel";
sql += " where rel.partyFrom = :partyFrom";
sql += " and rel.relationshipType= :typeName";
Query query = Organization.em().createQuery(sql);
query.setParameter("partyFrom", mgr1);
query.setParameter("typeName", "MANAGER");
List<Party> orgList = query.getResultList();
String sql2 = "";
sql2 = "select rel.partyFrom";
sql2 += " from Relationship rel";
sql2 += " where rel.partyTo = :partyToList";
sql2 += " and rel.relationshipType = :typeName2";
Query query2 = Organization.em().createQuery(sql2);
query2.setParameter("partyToList", orgList);
query2.setParameter("typeName2", "CUSTOMER");
List<Party> personList2 = query2.getResultList();
这两个查询都有效。查询 1 返回组列表,其中人 (mgr1) 与 MANAGER 有关系。查询 2 将他们是 CUSTOMER 的所有人员返回到查询 1 返回的组中。实际上,我得到了他们属于(客户)的人员列表,这些人员与人员(mgr1)有关系的同一组。
是否可以将它们组合成单个 sql 语句,因此可能只有一个 db 访问?