在ResultTransformer中正确投射 [英] Correct cast in ResultTransformer

查看:130
本文介绍了在ResultTransformer中正确投射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Hibernate结果转换器从数据库获取结果列表,如下所示:

 查询查询= em.createNativeQuery (SELECT 1 as myTrueBoolean,2 as myInt)
query.unwrap(org.hibernate.Query.class).setResultTransformer(Transformers.aliasT oBean(myDataClass));
query.fetchResultList()

比我能定义一个数据类如下: p>

  class MyDataClass {
boolean myTrueBoolean;
int myInt;





问题在于转换器不会正确地转换数据,因为它会分配BigInteger作为布尔值( IllegalArgumentException发生时调用setter的属性[MyDataClass.myTrueBoolean(expected type = boolean)]; target = MyDataClass,property value = [0]] )和与将BigInteger分配为int相同。这对于一般的Hibernate实体来说不是问题。



编辑:

我不是在寻找解释为什么它不起作用。我正在寻找一种方法使其工作:-)我需要这个为我的本地查询。有没有可能实现自己的变压器的方式来实现这一目标?解析方案

对于原生的SQL查询,您将得到任何数据库返回的结果。原生SQL查询就是这种情况。对于MySQL,它返回 BigInteger ,但对于 MsSQL ,它可以返回整数



将您的课程更改为

  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.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?

解决方案

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中正确投射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆