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

时间:2011-01-13 04:53:57

标签: java jpa jpql composite-key

我正在使用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].

3 个答案:

答案 0 :(得分:77)

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

答案 1 :(得分:3)

使用Hibernate 4.1和JPA 2.0进行测试

进行以下更改以便工作:

Class Machine.java

public class Machine {
   @EmbeddedId
   protected MachinePK machinePK;

   //getter & setters...
}

Class MachinePK.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());
}

答案 2 :(得分:0)

如果您使用注释@Query,则可以使用元素nativeQuery = true。