开发者

Hibernate - Use native query and alias to Bean with enum properties?

I am having trouble using a native query in hibernate to alias a bean that contains enum properties. I am getting an InvocationTargetException when query.list() is called. My example is below:

@Entity(name = "table1")
public class Class1 {
    @Column(name = "col1")
    @NotNull
    private Integer prop1;

    @Col开发者_如何转开发umn(name = "col2")
    @NotNull
    private String prop2;

    @Column(name = "col3", length = 6)
    @Enumerated(value = EnumType.STRING)
    private MyEnumType prop3;

    // ... Getters/Setters...
}

public List getClass1List(){
    String sql = "select col1 as prop1, col2 as prop2, col3 as prop3 from table1";

    Session session = getSession(Boolean.FALSE);
    SQLQuery query = session.createSQLQuery(sql);
    query.addScalar("col1", Hibernate.INTEGER);
    query.addScalar("col2", Hibernate.STRING);
    query.addScalar("col3", Hibernate.STRING);

    query.setResultTransformer(Transformers.aliasToBean(Class1.class));

    return query.list();
}

During the query.addScalar("col3", Hibernate.STRING) call, I don't know what type to use for col3 (the enum type). Hibernate.String is not working! I have also tried to leave the type off entirely ( query.addScalar("col3") ) but I get the same InvocationTargetException. Can anyone help me out with this? My model cannot be changed and I am stuck with a native sql query. Any ideas are appreciated.


// In public List getClass1List() method:
// 1. DEFINE:
Properties params = new Properties();
params.put("enumClass", "enumerators.MyEnumType");
params.put("type", "12");

// 2. REPLACE: 
// query.addScalar("col3", Hibernate.STRING);
// X

query.addScalar("col3", Hibernate.custom(org.hibernate.type.EnumType.class, params));


Firstly, you shouldn't use

private EnumType prop3;

but

private ActualEnum prop3;

Where ActualEnum is your own enum type (for example, Fruits to distinguish apples and oranges).

Second, you hibernate mapping is irrelevant when you use native sql.

Now, there are couple of options I can propose. You can try to use addEntity() instead of bunch of scalars. It's possible that Hibernate will recognize enum property and map correctly.

Other option is to have non public setter that would take string from database, convert it to enum and set actual property.

Finally, you can customize transformer. But it's probably most complex option.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜