2011-09-29 8 views
16

ho eseguire una query nativo JPA 2.0 in questo modo:JPA 2.0 risultati delle query native come mappa

Query query = em.createNativeQuery("SELECT NAME, SURNAME, AGE FROM PERSON"); 
List list = query.getResultList(); 

ora list ha tutte le righe restituite dalla query. Posso iterare su di loro, ma ogni voce è un Object[] dove:

  • indice 0 trovo NOME
  • all'indice 1 trovo COGNOME
  • al indice 3 Trovo AGE

qualcuno ha trovato un modo per fare qualcosa di simile:

Map<String, Object> row = list.get(index); 
String name = row.get("NAME"); 
String surname = row.get("SURNAME"); 
Integer age = row.get("AGE"); 
.210

avrei bisogno di questo dato che la query nativa che eseguo è dinamico e non so l'ordine del campo nella clausola SELECT, quindi non so id la query sarà simile:

SELECT SURNAME, NAME, AGE FROM PERSON 

o

SELECT AGE, NAME, SURNAME FROM PERSON 

o anche

SELECT AGE, SURNAME, NAME FROM PERSON 
+0

interrogazione criteri? http://www.ibm.com/developerworks/java/library/j-typesafejpa/ – NimChimpsky

+0

Io non la penso così, becase avrei ancora bisogno dietro Person.class. Come ho detto, il qeury SQL è dinamico e in realtà non so come sarà. – kovica

risposta

10

Quale APP stai usando - Hibernate, EclipseLink o qualcos'altro?

Non esiste un modo standard per fare questo in JPA, ma l'implementazione specifica può permettere - ad esempio, EclipseLink ha una query tipo di risultato suggerimento.

http://dev.eclipse.org/mhonarc/lists/eclipselink-users/msg03013.html

Query query = entityManager.createNativeQuery(sql); 
query.setHint(QueryHints.RESULT_TYPE, ResultType.Map); 

Per Hibernate, con javax.persistence.Query DBQuery:

org.hibernate.Query hibernateQuery =((org.hibernate.jpa.HibernateQuery)dbQuery) 
.getHibernateQuery(); 
hibernateQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE); 
+2

sembra Hibernate non avere un tale suggerimento :( – chrismarx

+2

Si sta lavorando per me utilizzando Query nativa in questo modo: ' NativeQueryImpl nativeQuery = (NativeQueryImpl) query,' ' nativeQuery.setResultTransformer (AliasToEntityMapResultTransformer.INSTANCE);' ' Lista > result = query.getResultList(); ' ' Mappa row = result.get (0); ' Valore stringa = (String) row.get (" NAME ") ; –

2

Date un'occhiata su questo ho preso quando si lavora su progetti che non ho potuto utilizzare tutte le funzioni JPA così ho provato il metodo JDBC tradizionale, anche se io non lo consiglio questo, ma che sta funzionando per me.

@LocalBean 
public class TCotisationEJB { 

    @PersistenceContext(unitName="ClaimsProjectPU") 
    private EntityManager em; 

    @TransactionAttribute(TransactionAttributeType.NEVER) 
    public List getCotisation(){ 
     Query query=em.createNativeQuery("select Annee,Mois,RetSonarwa from TCotisMIFOTRA2008 where matricule='10000493' order by Annee"); 
     List<Object[]> cotisation=query.getResultList(); 
     Object[] cotisationData; 

     for(int i=0;i<cotisation.size();i++){ 
       cotisationData=cotisation.get(i); 

      System.out.print("Annee: "+cotisationData[0]+" Mois :"+cotisationData[1]+" Amount  :"+cotisationData[2]+"\n"); 

    } 
    return query.getResultList(); 
    }  
} 
+1

Questo è esattamente ciò che l'OP vuole cambiare. – bargoras

1

Come altri già detto, più vecchio JPA non lo supporta, però ho la soluzione workaround con Postgres 9.4 nella mia situazione, mentre si lavora con Jackson,

List<String> list = em.createNativeQuery("select cast(json_object_agg(c.config_key,c.config_value) as text) from myschema.configuration c") 
        .getResultList(); 

di utilizzarlo in uso strato Bean sotto metodo, altrimenti restituire direttamente.

//handle exception here, this is just sample 
Map map = new ObjectMapper().readValue(list.get(0), Map.class); 

più funzioni JSON Poche, https://www.postgresql.org/docs/9.4/static/functions-json.html. Sono sicuro che puoi trovare lo stesso per altri database.

Problemi correlati