简体   繁体   中英

How to Persist a specific attribute of an Enum in Hibernate?

I have an enum attribute inside a backing bean which haves 2 attributes: "id" (int attribute) and "label" (String attribute). In the DB I need to persist only the "id", but I still need the label value to use on my view. The problem is: @Enumerated only gives me the option to persist using EnumType.ORDINAL or EnumType.STRING. There's any way to persist just the enum's "id" attribute in the DB? (btw... i'm using Hibernate).

Thanks!

fd's comment is in place. Nevertheless, if you're in a real need of this you can tweak the solution a bit, instead of persisting an enum, you can mark it as transient and add a property eg enumId to an entity class, that you'll persist instead. Than the only thing left is to synchronize the enum's value through getter and setter method of an enumId

The id and the attribute are two facets of the same thing. They have the same meaning. Storing them both in the DB is redundant, and violates the Third Normal Form of database design.

For a JPA (Hibernate) entity, I suggest you define the ORDINAL (which is the id) as your field and as suggested above by "Master Slave" define the String as a transient. Then define @PostLoad and the setter of the id to convert the ordinal to the name (which is your label) using name() and convert back using valueOf(String name) in the setter of the label.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM