问题
I have 2 entities Addemp and Job.I want to join these 2 tables based on empid .empid is foreign key in job table and primary key in addemp table
here i am doing a search operation based on employee id .i am using criteria builder for search operation
the relationship here is manytoone
public List<Object[]> findEmployeeList(Integer id)
{
EntityManager em=null;
try
{
em=getEntityManager();
CriteriaBuilder cb=em.getCriteriaBuilder();
CriteriaQuery cq=cb.createQuery(Addemp.class);
Root<Addemp>rt= cq.from(Addemp.class);
Join<Addemp,Job> job=rt.join(Addemp_.jobCollection);
Predicate predicate=cb.equal(rt.get("empId"),id);
cq.where(predicate);
/* cq.select(rt.get("firstName"));
cq.where (cb.equal(rt.<String>get("empId"),id));*/
Query qry= em.createQuery(cq);
return qry.getResultList();
回答1:
Based on the question and JPQL query from the above comments here is the criteria query proposal:
public List<Tuple> findEmployeeList(Integer id)
{
em = getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<Addemp> empRoot = cq.from(Addemp.class);
Root<Job> jobRoot = cq.from(Job.class);
cq.multiselect(empRoot.get("empId").alias("id"),
empRoot.get("firstName").alias("first"),
empRoot.get("lastName").alias("last"),
jobRoot.get("jobTitle").alias("title"),
jobRoot.get("empStatus").alias("status"),
jobRoot.get("subUnit").alias("subunit"));
cq.where(cb.equal(empRoot.get("empId"), id));
TypedQuery<Tuple> q = em.createQuery(cq);
return q.getResultList();
}
Next you may want to extract a tuple result:
List<Tuple> tuples = service.findEmployeeList(2);
for (Tuple t : tuples) {
StringBuilder builder = new StringBuilder(64)
.append(t.get("id")).append(", ")
.append(t.get("first")).append(", ")
.append(t.get("last")).append(", ")
.append(t.get("title")).append(", ")
.append(t.get("status")).append(", ")
.append(t.get("subunit"));
System.out.println(builder.toString());
}
I hope it helps.
来源:https://stackoverflow.com/questions/21671106/how-to-join-2-tables-based-on-passing-a-parameter-for-search-operation