JPA 2.0 native query results as map

后端 未结 3 713
难免孤独
难免孤独 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: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 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.

提交回复
热议问题