gpt4 book ai didi

Java : Set result set from JPA Paginated Query to custom class

转载 作者:太空宇宙 更新时间:2023-11-04 07:15:11 24 4
gpt4 key购买 nike

这是场景。

我正在尝试获取资源层中的记录列表。它有以下代码;

PagedResponse<Person> pagedResponse= new PagedResponse<Person>();

有一个对业务实现的调用

pagedResponse = facadeLocator.getPersonFacade().findAllRecords(getUserId(), fromrow, maxrows);

现在在业务实现中,我使用命名查询作为;

Query query = getNamedQuery("Person.findAll");

我的回复是

pagedResponse = executePagedQuery(query, firstResults, maxResults);

在executePagedQuery()内部,我有;

List resultList = query.getResultList();

返回的响应 pagedResponse 是自定义类型 PagedResponse 类,有 2 个成员;

private Long totalRecords;
private List<T> records;

现在在我的 Person 类中,我有

@NamedQuery(name = "Person.findAll", query = "Select DISTINCT(p.personName), p.personAge, p.personGender from Person p where p.personAge = :personAge")

现在这是运行时发生的情况。

我得到的“记录”为 vector ,成员为

[0] = Object[]
[1] = Object[]

回到资源层,我想迭代响应并将其设置在列表中

List<Person> personList = new ArrayList<Person>();

那么我有哪些选择。

我尝试过这样做

    for(Object[] person: pagedResponse.getRecords()) {
Person p = new Person();
p.setPersonName((String)person[0]);
// Setting other values
personList.add(p);
}

但它说该行的类型不兼容

for(Object[] person: pagedResponse.getRecords()) {

只是补充一下,当我的查询没有返回选择列而是返回所有列时,我没有遇到任何不兼容的类型问题;

query = "SELECT p FROM Person p WHERE 

所以我有两个问题;

1. Why was there no type casting issues when I was returning all the columns using the named query (It showed the type as "Person" and not generic type as showing after using the named query with specific columns)
2. Using the query with specific columns, what is the right approach to set the values returned from the query in the resource layer ?

最佳答案

具有许多单独SELECT值的查询应该返回一个列表列表。也许您想使用适当的构造函数来定义 bean:

package com.foo;

public class PersonData {
private String name;
private int age;
private Sex gender;

public PersonData(String name, int age, Sex gender) {
this.name = name;
this.age= age;
this.gender = gender;
}

// getters/setters
}

并将查询运行为:

SELECT NEW com.foo.PersonData(DISTINCT(p.personName), p.personAge, p.personGender)
FROM Person p WHERE p.personAge = :personAge

现在 getResultList() 应该返回 PersonData 对象的列表。虽然我没有使用嵌套的 new PersonData(DISTINCT(...)) 语法...

关于Java : Set result set from JPA Paginated Query to custom class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20071477/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com