开发者

Using Hibernate annotations to persist custom value for Enumerated attribute

开发者 https://www.devze.com 2023-02-11 06:46 出处:网络
I have lots of Java enums that I persist with Hibernate. As far as I know there are two different standard ways to persist these enums:

I have lots of Java enums that I persist with Hibernate. As far as I know there are two different standard ways to persist these enums:

@Enumerated(EnumType.ORDINAL)

This is the default, and it just persists the ordinal value from the enum.

@Enumerated(EnumType.STRING)

This persists the name of the enum value.

Those have worked fine for me so far, but now I have a new enum where I want to persist a custom value from the enum that is neither the ordinal nor the name. Is this possible? I searched around and saw lots of people asking how to persist the name, which is easily accomplished using EnumType.STRING, but I want to persist an int that can be used for comparison in my SQL queries. I tried overriding toString() to return my custom value, but that did not work.

I'll paste my java enum below. I want to persist t开发者_开发技巧he int value member from the enum.

Thanks in advance!

public enum Permission {
    VIEW (4),
    CHANGE(6),
    FULL(7);

    private int value;

    Permission(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}


You can implement a UserType with desired behaviour and configure Hibernate to use it with @Type annotation.

See, for example, UserType for persisting a Typesafe Enumeration with a VARCHAR column .


Yes, I'm missing a JPA solution, too.

Workaround:

  private int permissionValue;
  private transient Permission permission;

Then convert in the getter/setter of permission.

Maybe you also need to implement some lifecycle methods? (I'm not sure.) http://download.oracle.com/docs/cd/B32110_01/web.1013/b28221/undejbs003.htm#BABIAAGE

0

精彩评论

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