Enum 字段类型的 Hibernate SQL 转换失败 [英] Hibernate SQL transformation fails for Enum field type
问题描述
我正在使用 SQL 查询,然后使用 Hibernates 的 Transformers.aliasToBean()
转换结果.我的查询中的一列是枚举.枚举的转换以某种方式失败.我该怎么办?我应该使用哪种数据类型?我想要超过 1 个字符将结果转换为我的枚举类型.
I am using a SQL query and then transforming the result using Hibernates's Transformers.aliasToBean()
.
One of the columns in my query is an enum. The transformation somehow fails for the enum. What should I do? Which datatype should I use? I want more than 1 character to transform the result into my enum type.
这是我的查询/代码的简化版本的样子(b 是表配置文件中的枚举):
This is how the simplified version of my query/code looks like (b is an enum in the table profiles):
session.createSQLQuery("select a, b from profiles").setResultTransformer(Transformers.aliasToBean(Profile.class))
.list();
异常:预期类型:Foo.ProfileStateEnum,实际值:java.lang.Character
推荐答案
假设 b 列对应的 java 枚举类型是 Foo.ProfileStateEnum,下面的代码片段应该适合你.(我用 Hibernate 4.1.6 测试过)
Assuming that the java enum type that corresponds to column b is Foo.ProfileStateEnum, the following code snippet should work for you. (I tested with Hibernate 4.1.6)
import java.util.Properties;
import org.hibernate.type.Type;
import org.hibernate.type.IntegerType;
import org.hibernate.internal.TypeLocatorImpl.TypeLocatorImpl;
import org.hibernate.type.TypeResolver.TypeResolver;
import org.hibernate.type.EnumType;
Properties params = new Properties();
params.put("enumClass", "Foo.ProfileStateEnum");
params.put("type", "12"); /*type 12 instructs to use the String representation of enum value*/
/*If you are using Hibernate 5.x then try:
params.put("useNamed", true);*/
Type myEnumType = new TypeLocatorImpl(new TypeResolver()).custom(EnumType.class, params);
List<Profile> profileList= getSession().createSQLQuery("select a as ID, b from profiles")
.addScalar("ID", IntegerType.INSTANCE)
.addScalar("b", myEnumType )
.setResultTransformer(Transformers.aliasToBean(Profile.class))
.list();
这篇关于Enum 字段类型的 Hibernate SQL 转换失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!