问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/44585825/correct-cast-in-resulttransformer