我是新的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应该使用实体名称,默认是类的名称。 AssignTaskEmployee
它应该是
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