How to write JPQL SELECT with embedded id?

后端 未结 3 1177
温柔的废话
温柔的废话 2020-12-13 08:33

I\'m using Toplink essentials (JPA) + GlassFish v3 + NetBean 6.9

I have one table with composite primary key:

table (machine)
----------------
|PK ma         


        
3条回答
  •  既然无缘
    2020-12-13 09:24

    Tested with Hibernate 4.1 and JPA 2.0

    Make the following changes in order to work:

    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...
    }
    

    ...and for the JPQL query pass all column names:

    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 objPKList = new ArrayList();
    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());
    }
    

提交回复
热议问题