假设我的DAO中有这个nativeQuery:
SELECT a, b, c FROM table返回我需要的所有值。
问题是我有太多的结果和,我需要这个查询只运行一次,而不是运行找到的每一行。
我正在检索查询结果,并将所有值设置为一个名为Class的类(value对象),如下所示:
public List<Class> listClass() {
List<Class> listaObjs;
String nativeQuery = "SELECT a, b, c FROM table";
SQLQuery q = getSession().createSQLQuery(nativeQuery);
int totalRecords = q.list().size();
System.out.println("Total records: " + totalRecords);
listaObjs = q.list();
// For every ROW in query Result
for (int i = 0; i < totalRecords; i++) {
Object[] objs = (Object[]) q.list().get(i);
Class item = new Class();
// For every COLUMN in that ROW
for (Object obj : objs) {
item.setValueA((String) objs[0]);
item.setValueB(((String) objs[1]));
item.setValueC(((String) objs[2]));
listaObjs.add(item);
}
}
return listaObjs;
}我被困在这里了,因为我以前从来没有把这个Object[]当Class演员。
发布于 2015-10-23 19:30:24
更改以下行
// For every ROW in query Result
for (int i = 0; i < totalRecords; i++) {
Object[] objs = (Object[]) q.list().get(i);使用
List<Object[]> objArr = q.list();
// For every ROW in query Result
for (int i = 0; i < totalRecords; i++) {
Object[] objs = (Object[]) objArr.get(i);发布于 2015-10-23 19:30:26
您的代码有很多性能和编程问题。请在下面试试。
public List<Class> listClass() {
List<Class> listaObjs = new ArrayList<Class>();
String nativeQuery = "SELECT a, b, c FROM table";
SQLQuery q = getSession().createSQLQuery(nativeQuery);
List<Object[]> totalRecords = q.list();
System.out.println("Total records: " + totalRecords.size());
for (Object[] objects : totalRecords) {
Class item = new Class();
item.setValueA((String) objs[0]);
item.setValueB(((String) objs[1]));
item.setValueC(((String) objs[2]));
listaObjs.add(item);
}
return listaObjs;
}发布于 2015-10-23 19:29:33
此代码将在每次迭代中重新运行查询:
Object[] objs = (Object[]) q.list().get(i);您已经在listaObjs = q.list();中获得了列表,所以在循环中处理listaObjs:
for (int i = 0; i < totalRecords; i++) {
Object[] objs = (Object[])listaObjs.get(i);https://stackoverflow.com/questions/33309988
复制相似问题