JPA 2.0 native query results as map

后端 未结 3 708
难免孤独
难免孤独 2020-12-01 14:25

I run a JPA 2.0 native query like this:

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


        
相关标签:
3条回答
  • 2020-12-01 14:42

    Take a look on this I got it when working on project that I could not use all JPA features so I tried the traditional jdbc method even if I would not recommend this but it's working for 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();
         }    
    }
    
    0 讨论(0)
  • 2020-12-01 14:45

    Which JPA are you using - Hibernate, EclipseLink or something else?

    There is no standard way to do this in JPA but your specific implementation may allow it - for example, Eclipselink has a query result type hint.

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

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

    For Hibernate, with javax.persistence.Query dbQuery:

    org.hibernate.Query hibernateQuery =((org.hibernate.jpa.HibernateQuery)dbQuery)
    .getHibernateQuery();
    hibernateQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
    
    0 讨论(0)
  • 2020-12-01 14:48

    As other already mentioned, older JPA does not support it, however I have workaround solution with Postgres 9.4 in my situation, while working with Jackson,

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

    To use it in Bean layer use below method, otherwise directly return.

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

    Few more json functions, https://www.postgresql.org/docs/9.4/static/functions-json.html. I am sure you can find same for other databases.

    0 讨论(0)
提交回复
热议问题