Learning how to write a JPA request. Please tell me if it is possible to write the following queries more efficiently, maybe in one select statement. Maybe join, but not sure how to do it.
class Relationship {
@ManyToOne
public String relationshipType;
@ManyToOne
public Party partyFrom;
@ManyToOne
public Party partyTo;
}
Inquiries
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();
Both requests work. Query 1 returns a list of groups in which the person (mgr1) has a relationship of MANAGER s. Query 2 returns all the persons to which they belong to the groups returned by query 1. In fact, I get a list of the Persons to whom they belong (the client) of the same group where Person (mgr1) is related to MANAGER c.
Is it possible to combine them into one SQL query, perhaps only one db access?
source
share