gpt4 book ai didi

java - 加入 JPQL、CreateQuery

转载 作者:行者123 更新时间:2023-12-01 20:12:08 27 4
gpt4 key购买 nike

尝试弄清楚 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();

假设用户在 strMgr 中输入“ill gat”值来搜索经理姓名“Bill Gates”。它应该搜索经理比尔盖茨下的员工。但在这段代码中出现了 ff 错误:

IllegalArgumentException: Cannot create TypedQuery for query with more than one return using requested result type [models.db.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;

我自己将经理加入到员工中作为“经理”

最佳答案

事情是,当查询中有多个实体时,您必须指定想要哪个实体作为结果(除非它是投影)。

query.append(" SELECT e")
query.append(" FROM ");
query.append(" Employee e ");
query.append(" JOIN ");
query.append(" e.Manager m ");

SELECT m(如果您希望将经理作为结果)。

LIKE 子句很好......它的构建是为了防止 SQL 注入(inject)。

关于java - 加入 JPQL、CreateQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46523205/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com