如何用嵌入式ID编写JPQL SELECT?

2022-08-31 19:51:04

我正在使用Toplink essentials (JPA) + GlassFish v3 + NetBean 6.9

我有一个带有复合主键的表:

table (machine)
----------------
|PK machineId  |
|PK workId     |
|              |
|______________|

我创建了2个实体类,一个是实体本身,第二个是PK类。

public class Machine {
   @EmbeddedId
   protected MachinePK machinePK;

   //getter setters of fields..
}

public class MachinePK {
    @Column(name = "machineId")
    private String machineId;

    @Column(name = "workId")
    private String workId;

}

现在。。如何使用 WHERE 使用 JPQL 编写 SELECT 子句???

此操作将失败。

SELECT m FROM Machine m WHERE m.machineId = 10

http://www.mail-archive.com/users@openjpa.apache.org/msg03073.html

根据网页,添加“val”?不,它也失败了。

   SELECT m FROM Machine m WHERE m.machineId.val = 10

在这两种情况下,错误都是:

    Exception Description: Error compiling the query 
[SELECT m FROM Machine m WHERE m.machineId.val = 10], 
line 1, column 30: unknown state or association field 
[MachineId] of class [entity.Machine].

答案 1
SELECT m FROM Machine m WHERE m.machinePK.machineId = 10

答案 2

使用休眠 4.1 和 JPA 2.0 进行测试

进行以下更改才能正常工作:

计算机.java

public class Machine {
   @EmbeddedId
   protected MachinePK machinePK;

   //getter & setters...
}

机器PK.java

@Embeddable
public class MachinePK {
    @Column(name = "machineId")
    private String machineId;

    @Column(name = "workId")
    private String workId;

    //getter & setters...
}

...对于 JPQL 查询,传递所有列名:

Query query = em.createQuery("SELECT c.machinePK.machineId, c.machinePK.workId, "
                + "FROM Machine c WHERE c.machinePK.machineId=?");
query.setParameter(1, "10");

Collection results = query.getResultList();

Object[] obj = null;
List<MachinePK> objPKList = new ArrayList<MachinePK>();
MachinePK objPK = null;
Iterator it = results.iterator();
while(it.hasNext()){
    obj = (Object[]) it.next();
    objPK = new MachinePK();
    objPK.setMachineId((String)obj[0]);
    objPK.setWorkId((String)obj[1]);
    objPKList.add(objPK);
    System.out.println(objPK.getMachineId());
}

推荐