使用Hibernate Annotations映射多个值枚举类型

时间:2018-03-07 09:17:51

标签: sql hibernate enums hql transformation

为了将Hibernate查询结果映射到包含枚举的自定义类,我应该这样做according to this post,但我不想使用枚举字段名称,而是使用其多个值之一:

Properties params = new Properties();
params.put("enumClass", "MyStatusEnum");
params.put("useNamed", true)

String sql = "SELECT "
    + "PRICE as price, "
    + "COMPANY as companyId, "
    + "NAME as name, "
    + "STATUS as statusEnum "
    + "FROM `FUC**** TABLE WITH SPACE`";

List <Item> items = session.createNativeQuert(sql) // Obliged to use this method 
// with deprecated transformer after because createQuery does not 
// recognize ` escape character and if I use session.createQuery(sql, Item.class), 
// Item is not recognized as an entity ...
    .addScalar(price) // Obliged to do it for all fields just because I need to do it for one field ?!
    .addScalar(companyId)
    .addScalar(name)
    .addScalar(statusEnum)
    .setResultTransformer(Transformers.aliasToBean(Item.class)).list();

1)问题出在MyEnum.AVAILABLE上,例如,数据不是“可用”而是一个int,所以这是我的枚举:

public enum MyEnum {
    AVAILABLE(0, 1),
    TO_SENT(1, null),
    ARCHIVED(2, null);

    private final int stateNum;

    private final Integer nextStateNum;

    MyEnum(int stateNum, Integer nextStateNum) {
        this.stateNum = stateNum;
        this.nextStateNum = nextStateNum;
    }
}

我想将DB中的STATUS(可能的值:0,1,2)映射到名称而不是第一个属性代码(stateNum),如何做到这一点? Coul我应用一个函数从代码中获取枚举?

Properties params = new Properties();
params.put("enumClass", "Foo.ProfileStateEnum");
params.put("???", "???");

2)如何获取有关属性映射到枚举的文档以及hibernate&lt; 5,我们必须使用params.put(“type”,“12”);,哪里是相应的doc?

非常感谢,

1 个答案:

答案 0 :(得分:0)

答案1):Mapping Enum Types with Hibernate Example是我正在测试的曲目,但我不会使用注释而是代码。

回答2):Class EnumType