【问题标题】:Hibernate Custom SQL Enum transformation failsHibernate 自定义 SQL 枚举转换失败
【发布时间】:2017-05-02 22:13:05
【问题描述】:

这里有类似的问题,但没有一个对我有用。我有一个自定义 SQL,它返回 2 列:一个字符串,一个数字。并且字符串列始终是一个完整的大写 ENUM 名称。我想将此结果集提供给具有上述枚举的自定义 bean。

按照 Hibernate 5.X 的答案 here,代码如下

    Properties params = new Properties();
    params.put("enumClass", "MyEnumClass");
    params.put("useNamed", true);
    Type myEnumType = new TypeLocatorImpl(new TypeResolver()).custom(MyEnumClass.class, params);

    final Query query = getCurrentSession().createSQLQuery(MY_CUSTOM_SQL)
            .addScalar("col1", myEnumType)
            .addScalar("col2", StandardBasicTypes.INTEGER)
            .setLong("someSqlVar", someVal)
            .setResultTransformer(Transformers.aliasToBean(MyCustomBean.class));

    return query.list();

这段代码甚至没有执行 query.list() 方法,它在这一行失败:

Type myEnumType = new TypeLocatorImpl(new TypeResolver()).custom(MyEnumClass.class, params);

异常跟踪:

Caused by: org.hibernate.MappingException: Unable to instantiate custom type: com.example.MyEnumClass
...
Caused by: java.lang.InstantiationException: com.example.MyEnumClass
...
Caused by: java.lang.NoSuchMethodException: com.example.MyEnumClass.<init>()
at java.lang.Class.getConstructor0(Class.java:3082) ~[?:1.8.0_60]
at java.lang.Class.newInstance(Class.java:412) ~[?:1.8.0_60]
at org.hibernate.type.TypeFactory.custom(TypeFactory.java:202) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.type.TypeFactory.custom(TypeFactory.java:193) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.internal.TypeLocatorImpl.custom(TypeLocatorImpl.java:144) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
...

所以休眠尝试调用MyEnumClass.class.newInstance() 并失败。它甚至不检查我通过的属性。使用 Hibernate 5.1.0.Final,我不应该这样使用自定义类型吗?

【问题讨论】:

    标签: sql hibernate enums transformation


    【解决方案1】:

    我找到了一种方法:

    Properties params = new Properties();
    params.put("enumClass", MyEnumClass.class.getName());
    params.put("useNamed", true);
    
    EnumType enumType = new EnumType();
    enumType.setParameterValues(params);
    CustomType customType = new CustomType(enumType);
    
    final Query query = getCurrentSession().createSQLQuery(MY_CUSTOM_SQL)
       .addScalar("col1", customType)
       .addScalar("col2", StandardBasicTypes.INTEGER)
       .setLong("someSqlVar", someVal)
       .setResultTransformer(Transformers.aliasToBean(MyCustomBean.class));
    
    return query.list();
    

    【讨论】:

    • 白夜过后,发现了这个!就像 Hibernate 5.1.0 的魅力一样!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 2012-06-01
    • 2018-04-23
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多