gpt4 book ai didi

java - jpa复合主键表不返回值

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

我是新的 JPA,当我从复合主键表中检索值时遇到异常。

异常描述:

Problem compiling [select t from ASSIGN_TASK_EMPLOYEE t]. 
[14, 34] The abstract schema type 'ASSIGN_TASK_EMPLOYEE' is unknown.
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1605)

以下是我的代码

@Entity
@Table(name = "ASSIGN_TASK_EMPLOYEE")
//@IdClass(AssignTaskEmployeePk.class)
public class AssignTaskEmployee implements Serializable {

@EmbeddedId
private AssignTaskEmployeePk assignTaskEmployeePk;

public AssignTaskEmployeePk getAssignTaskEmployeePk() {
return assignTaskEmployeePk;
}

public void setAssignTaskEmployeePk(AssignTaskEmployeePk assignTaskEmployeePk) {
this.assignTaskEmployeePk = assignTaskEmployeePk;
}

}

@Embeddable
public class AssignTaskEmployeePk {

private String employeeId;
private String taskId;
public AssignTaskEmployeePk() {
}

@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub

if (obj instanceof AssignTaskEmployeePk) {

AssignTaskEmployeePk employeePk = (AssignTaskEmployeePk) obj;
if (!employeePk.getEmployeeId().equals(this.employeeId)) {
return false;
}
else if (!employeePk.getTaskId().equals(this.taskId)) {
return false;
}

}
else {
return false;
}

return false;

}

@Override
public int hashCode() {
return employeeId.hashCode() + taskId.hashCode() ;
}

public String getEmployeeId() {
return employeeId;
}

public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}

public String getTaskId() {
return taskId;
}

public void setTaskId(String taskId) {
this.taskId = taskId;
}


}

我在数据库中为复合主键 ASSIGN_TASK_EMPLOYEE(表)添加了四个值,其中 PK 表

EMP_ID   TASKID
1 2
2 4
3 5
4 6

现在我想获取分配给 emp_id 1 的任务为此,我编写了下面的查询:这应该返回AssignTaskEmployee对象的列表。

entityManager.createQuery("select t from ASSIGN_TASK_EMPLOYEE t").getResultList()

当我执行此查询时,出现以下异常

Exception Description: 

Problem compiling [select t from ASSIGN_TASK_EMPLOYEE t].
[14, 34] The abstract schema type 'ASSIGN_TASK_EMPLOYEE' is unknown.
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1605)

最佳答案

JPQL应该使用实体名称,默认是类的名称。分配任务员工

应该是

entityManager.createQuery("select t from AssignTaskEmployee  t").getResultList()

以上将返回表ASSIGN_TASK_EMPLOYEE中的所有记录。

如果您想使用 JPQL 检索特定记录,您应该使用 WHERE 语句,如下所示:

    Query query =  entityManager.createQuery("select t from AssignTaskEmployee t WHERE 
t.assignTaskEmployeePk.employeeId = :employeeId and t.assignTaskEmployeePk.taskId = :taskId")

query.setParameter("employeeId", 1);
query.setParameter("taskId",1);

query.getSingleResult() //As expected to have only one record.

阅读this通过EmbeddedId查询

关于java - jpa复合主键表不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21475322/

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