Correct cast in ResultTransformer

无人久伴 提交于 2019-12-24 19:06:08

问题


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.aliasT‌​oBean(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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!