将您的课程更改为
class MyDataClass {
Number myTrueBoolean;
Number myInt;
}
另一种选择是使用JPA查询。他们将从您的实体返回值的类型。
I am using Hibernate result transformer for fetching list of results from the database as follows:
Query query = em.createNativeQuery("SELECT 1 as myTrueBoolean, 2 as myInt")
query.unwrap(org.hibernate.Query.class).setResultTransformer(Transformers.aliasToBean(myDataClass));
query.fetchResultList()
Than I could define a data class as follows:
class MyDataClass {
boolean myTrueBoolean;
int myInt;
}
The problem is that the transformer will not cast correctly the data as it will assign BigInteger as boolean (IllegalArgumentException occurred while calling setter for property [MyDataClass.myTrueBoolean (expected type = boolean)]; target = MyDataClass, property value = [0]]
) and the same with assigning BigInteger as int. This wouldn't be a problem with general Hibernate entities.
EDIT:
I am not looking for explanation why it does not work. I am looking for a way to making it work :-) I need this for my native queries. Is there maybe a way of implementing own transformer which would achieve this?
解决方案
For native SQL queries you get whatever the database returns. That is kind of the point with native SQL queries. For MySQL it returns BigInteger
,but for MsSQL
it can return Integer
.
Change your class to
class MyDataClass {
Number myTrueBoolean;
Number myInt;
}
Another option is to use JPA queries. They will return types of values from your entities.
这篇关于在ResultTransformer中正确投射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!