如何从自定义Hibernate查询填充POJO类? [英] How to populate POJO class from custom Hibernate query?
问题描述
我是Hibernate的新手,并试图在Spring MVC应用程序中使用它。我有如下的自定义查询:
findEmployees(){String queryString =选择E.firstname,E.lastname,A.city,A.state $ b $ from Employee E,Address A,where ....; //任何where子句
SQLQuery查询= this.sessionFactory.getCurrentSession()。createSQLQuery(queryString);
query.setString(...)//设置查询参数
return query.list();
}
这不起作用。查询运行,但它返回一个对象列表。
如何让Hibernate使用我的 MyResults
类?
class MyResults {
private String firstName;
//搜索中的其他字段
@Column(name =FirstName)
String getFirstName(){
return firstName;
}
void setFirstName(String firstName){
this firstName = firstName;
}
//其他getters& setters
}
我也不确定注释 MyResults
我试过几件事: return(List< MyResults>)query.list();
虽然这种转换不行。
我尝试过使用ResultTransformer:
query.setResultTransformer(新的AliasToBeanResultTransformer(MyResults.class)); //在返回之前完成
但导致
ClassClastException:MyResults不能转换为java.util.Map。
有人可以显示我如何在Hibernate中正确设置这种查询?
ClassClastException:MyResults无法转换为java.util.Map
是Hibernate将列名的别名转换为大写 - firstName
变为 FIRSTNAME
。而且它确实需要 DTO
中的setter setFIRSTNAME()
。不知道,这是一个错误或功能。 要解决这个问题,请参阅我的回答你的其他问题:
I'm new to Hibernate, and trying to use it in a Spring MVC application. I have a custom query like the following:
public List<MyResults> findEmployees() {
String queryString = "select E.firstname, E.lastname, A.city, A.state
from Employee E, Address A, where ...."; // whatever where clause
SQLQuery query = this.sessionFactory.getCurrentSession().createSQLQuery(queryString);
query.setString(...) // set query parameters
return query.list();
}
This doesn't work. The query runs, but it returns a list of objects.
How do I tell Hibernate to use my MyResults
class?
class MyResults {
private String firstName;
// other fields in the search
@Column(name = "FirstName")
String getFirstName() {
return firstName;
}
void setFirstName(String firstName) {
this firstName = firstName;
}
// other getters & setters
}
I'm also not sure what annotations MyResults
needs?
I've tried a couple things:
return (List<MyResults>)query.list();
though this cast doesn't do it.
I've tried using a ResultTransformer:
query.setResultTransformer(new AliasToBeanResultTransformer(MyResults.class)); //done before the return
but that causes an
ClassClastException: MyResults cannot be cast to java.util.Map.
Can someone show me how to set this kind of query up correctly in Hibernate?
The cause of ClassClastException: MyResults cannot be cast to java.util.Map
is that Hibernate converts aliases for column names to upper case — firstName
becomes FIRSTNAME
. And it is really need the setter setFIRSTNAME()
in the DTO
. Don't know, it is a bug or feature.
To solve this issue, please, see my answer to your other question:
mapping Hibernate query results to custom class?
这篇关于如何从自定义Hibernate查询填充POJO类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!