简体   繁体   English

将对象数组映射到Bean

[英]Map Object Array to a Bean

I am making an SQL query via JPA and getting a List of Object Arrays. 我通过JPA进行SQL查询并获取对象数组列表。 I wish to map these Object Arrays into a bean. 我希望将这些对象数组映射到bean中。

For example, my query gives me the following output. 例如,我的查询给我以下输出。

List<Object[]> list = // myWorkingJpaQuery;
// list is of length 2. 
// Each Object array always holds a Long in index 0, 
// a TimeStamp in index 1 and a String in index 2. 

Instead of reading these values and performing casting, I wish to map it to a class as follows: 我不想读取这些值并进行强制转换,而是希望将其映射到以下类:

class ExampleClass{
    //all these variables matches the aliases in myWorkingJpaQuery.
    Long id;
    TimeStamp ts;
    String name;
    // get set
}  

Tried to use the above class my changing the JPA methods return type and assigning it in the calling class as follows but it doesn't work. 试图使用上述类,我改变了JPA方法的返回类型并按如下方式在调用类中进行了分配,但这是行不通的。

List<ExampleClass> list = // myWorkingJpaQuery with List<ExampleClass> as return type;

Is there a way to do this? 有没有办法做到这一点? It is currently working fine if I stick to Object Array but just trying not to use Objects and castings. 如果我坚持使用Object Array,但只是尝试不使用Objects和Casting,则目前工作正常。 For reference, I am using Spring. 供参考,我正在使用Spring。

Does your ExampleClass have a constructor ? 您的ExampleClass是否有构造函数? if yes you should be able to do the following : 如果是,您应该可以执行以下操作:

List<ExampleClass> myList = new ArrayList<ExampleClass>();
List<Object[]> list = // myWorkingJpaQuery;
for (int i = 0; i < list.size(); i++) {
        ExampleClass obj = new ExampleClass(list.get(i)[0],list.get(i)[1],list.get(i)[2]);
        myList.add(obj);
    }

And your done 和你完成

Assuming you're using the native query (otherwise, the ORM tool will do this for you automatically): 假设您使用的是本机查询(否则,ORM工具将自动为您执行此操作):

You might have a code like this: 您可能有这样的代码:

 EntityManager em = ...
 Query q = em.createNativeQuery("SELECT ...");
 List<Object[]> results = q.getResultList();

In this case, you might consider passing an additional parameter to createNativeQuery method: 在这种情况下,您可以考虑将其他参数传递给createNativeQuery方法:

 Query q = em.createNativeQuery("SELECT...", ExampleClass.class);
 List<ExampleClass> results = q.getResultList();

For more complicated/customized Mappings consider using Result Set Mappings feature 对于更复杂/自定义的映射,请考虑使用结果集映射功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM