How to write JPQL SELECT with embedded id?
SELECT m FROM Machine m WHERE m.machinePK.machineId = 10
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<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());
}