2011-01-13 7 views
34

Sto utilizzando Informazioni Toplink (JPA) + GlassFish v3 + NetBean 6,9Come scrivere JPQL SELECT con ID incorporato?

Ho una tabella con chiave primaria composta:

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

Ho creato 2 classi entità uno per entità stessa e la seconda è PK classe.

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; 

} 

Ora .. Come faccio a scrivere clausola SELECT con JPQL con DOVE ???

Questo fallisce.

SELECT m FROM Machine m WHERE m.machineId = 10 

http://www.mail-archive.com/[email protected]/msg03073.html

Secondo la pagina web, aggiungere "val"? No, fallisce anche lui.

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

In entrambi i casi, l'errore è:

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

risposta

64
SELECT m FROM Machine m WHERE m.machinePK.machineId = 10 
+0

Grazie! funziona: D –

+0

@ Masato-san: sei il benvenuto. –

+0

Come convertirlo in criteri JPA? –

1

testato con Hibernate 4.1 e JPA 2.0

Apportare le seguenti modifiche al fine di lavorare:

Classe Machine.java

public class Machine { 
    @EmbeddedId 
    protected MachinePK machinePK; 

    //getter & setters... 
} 

Classe MachinePK.java

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

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

    //getter & setters... 
} 

... e per la query JPQL passare tutti i nomi delle colonne:

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()); 
} 
0

Se si utilizza l'annotazione @Query, è possibile utilizzare elemento nativeQuery = true.