java - Map Object Array to a Bean
问题描述
I am making an SQL query via JPA and getting a List of Object Arrays. I wish to map these Object Arrays into a 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.
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. For reference, I am using Spring.
解决方案
您的 ExampleClass 是否有构造函数?如果是,您应该能够执行以下操作:
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);
}
你完成了
推荐阅读
- tcp - 我的路由器在端口 111 上进行活动是否正常?
- r - R如何匹配和提取字符串中不同长度的字符字母
- python - 当线段有序但线段的方向是随机的时,有效地对线段列表进行排序
- http - HTTP 状态 404 - 未找到解决方案
- json - 使用 Python 从目录运行和读取
- python - 使用 django-simple-history 和 django-queryable-properties 在 Django 查询集中添加历史字段值
- python - Python - 使用 cx_Freeze 构建二进制文件时,代码保存在哪里?
- python - 检测 Jupyter notebook 时 tqdm 失败
- field - 复制字段配置以在表单 API 中创建新的类似字段
- android - Android 中的捐款