试图弄清楚JPQL CreateQuery的连接是如何工作的。我有一个部分搜索功能,用于管理员名称和SQL代码:
SELECT
e.EMPLOYEE_ID AS empId,
e.FIRST_NAME AS empFirstName,
e.LAST_NAME AS empLastName,
m.FIRST_NAME || ' ' || m.LAST_NAME AS empMgrName
FROM
EMPLOYEES e
LEFT JOIN
EMPLOYEES m ON e.MANAGER_ID = m.EMPLOYEE_ID
WHERE
LOWER(m.FIRST_NAME || ' ' || m.LAST_NAME) LIKE '%"ManagerName"%'
我尝试将其转换为JPQL格式,我想出了以下内容:
StringBuilder query = new StringBuilder();
query.setLength(0);
query.append(" FROM ");
query.append(" Employee e ");
query.append(" JOIN ");
query.append(" e.Manager m ");
query.append(" WHERE 1 = 1 ");
query.append(" LOWER(m.FIRST_NAME || ' ' || m.LAST_NAME) LIKE :empMgrName ");
Query listEmpQuery = JPA.em().createQuery(query.toString(), Employee.class);
if (!StringUtil.isNullOrEmpty(strMgr)) {
listEmpQuery.setParameter("empMgrName", "%" + strMgr.toLowerCase() + "%");
}
List<Employee> listEmp = listEmpQuery.getResultList();
假设用户输入“ill gat”的值到strMgr
以搜索经理名称“Bill Gates”。它应该搜索经理账单门下的员工。但是在这段代码中会出现ff错误:
IllegalArgumentException: Cannot create TypedQuery for query with more than one return using requested result type [models.db.Employee]]
我做错了什么?
参考: Employee.class
@Entity
@Table(name="EMPLOYEES")
@SequenceGenerator(name = "EMPLOYEES_SEQ", sequenceName = "EMPLOYEES_SEQ")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "EMPLOYEES_SEQ")
public Integer EMPLOYEE_ID;
public String FIRST_NAME;
public String LAST_NAME;
@OneToOne
@JoinColumn(name="MANAGER_ID")
public Employee Manager;
我自己将经理加入员工作为“经理”
答案 0 :(得分:2)
事情是,当你在查询中有多个实体时,你必须指定你想要的那个实体(除非它是一个投影)。
query.append(" SELECT e")
query.append(" FROM ");
query.append(" Employee e ");
query.append(" JOIN ");
query.append(" e.Manager m ");
或SELECT m
如果您想将经理作为结果。
LIKE
子句很好..它是为防止sql注入而构建的。
答案 1 :(得分:1)
你想要实现的是LEFT OUTER FETCH JOIN:
query.append("SELECT e FROM ");
query.append(" Employee e ");
query.append("LEFT JOIN FETCH ");
query.append(" e.Manager");
query.append(" WHERE LOWER(CONCAT(m.FIRST_NAME, ' ', m.LAST_NAME)) LIKE :empMgrName ");