JPA Query.getResultList() - 以通用方式使用 [英] JPA Query.getResultList() - use in a generic way

查看:825
本文介绍了JPA Query.getResultList() - 以通用方式使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用多个表创建复杂查询,并需要列出结果。通常,我使用 EntityManager 并将结果映射到JPA表示:

  UserEntity user = em.find(UserEntity.class,5); 

然后我可以以用户 UserEntity 类定义它。但是,我如何访问从本地多表查询返回的字段值呢?我得到的是一个对象列表。到目前为止,这很好,但是那个Object是什么?阵列?地图?采集? ...

  // simpleExample 
查询查询= em.createNativeQuery(SELECT u.name,s.something FROM用户u,someTable s WHERE s.user_id = u.id);
List list = query.getResultList();

//做某事。与列表,例如访问每个结果行的东西。

我猜这个答案很简单,但是大多数例子都显示直接投射到一个targetClass。



PS:在这个例子中,我可以使用class-mappings当然。但在我的情况下, someTable 不是由JPA管理的,因此我没有该实体,也没有它的类表示,并且自加入就像20个表一样,我不想创建所有的类来访问这些值。解析方案

通常的规则如下:




  • 如果选择包含单个表达式并且它是一个实体,那么结果是实体

  • 如果选择包含单个表达式并且它是一个基元,那么结果就是该基元

  • 如果选择包含多个表达式,那么结果是 Object [] 包含相应的基元/实体




  • 因此,在你的情况下 list 是一个 List< Object [] >


    I'm creating a complex query with multiple tables and need to list the result. Usually, I'm using the EntityManager and map the result to the JPA-Representation:

    UserEntity user = em.find(UserEntity.class, "5");
    

    Then I can access all values as the user UserEntity class defines it. But how can I access the field-values returned from a native, multiple-table query? What I get is a List of Objects. That's fine so far, but what "is" that Object? Array? Map? Collection? ...

    //simpleExample
    Query query = em.createNativeQuery("SELECT u.name,s.something FROM user u, someTable s WHERE s.user_id = u.id");
    List list = query.getResultList();
    
    //do sth. with the list, for example access "something" for every result row.
    

    I guess the answer is quite simple, but most examples out there just show the usage when directly casting to a targetClass.

    PS: In the example I could use the class-mappings of course. But in my case someTable is not managed by JPA, and therefore I don't have the entity nor do I have a class-representation of it, and since I'm joining like 20 tables, I don't want to create all the classes just to access the values.

    解决方案

    General rule is the following:

    • If select contains single expression and it's an entity, then result is that entity
    • If select contains single expression and it's a primitive, then result is that primitive
    • If select contains multiple expressions, then result is Object[] containing the corresponding primitives/entities

    So, in your case list is a List<Object[]>.

    这篇关于JPA Query.getResultList() - 以通用方式使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆