Persist raw Java Enum with Hibernate

I have an object that contains an enum property. This property can be any of my Enums types in my code base:

public enum AutomobileType { CAR, TRUCK, MOTORCYCLE } public enum BoatType { ROW_BOAT,YACHT,SHIP } @Entity public class FooBar { @Enumerated(value=EnumType.ORDINAL) private Enum enumValue; public void setEnumValue(Enum value) { ... } public Enum getEnumValue() { ... } } 

This fails with the exception: โ€œInvalid data type: for input string:โ€œ [B @ f0569a. โ€I changed FooBar to save the property as an integer that works, but thatโ€™s not what I need. I need an actual listing Any suggestions on how to make this work so that Enum can be saved as an int, but later pulled into the correct Enum type?

+6
java enums hibernate jpa
source share
3 answers

You need to define a custom UserType for Enum.

+3
source share

As a rule, you should not do this. If two (or more enumerations) can be assigned the same field, combine them into one anum.

If you use inheritance, for example: Vehicle with two subclasses - Boat and Car , then you can have a different field in each subclass - after all, each of these enumerations refers only to a certain type, So:

 @Column private BoatType boatType; 
+2
source share

I do not think this can easily work with several types of Enum trying to coexist in the same property. How does hibernate know which Enum class it should create when it loads a field from the database?

If you really want to do this, you need to somehow encode the enum class + value each time you save this property (use a custom UserType, as duffymo suggests).

Can't you break this down into two properties, one per enum class? You can then declare enumValue (and enumValue2) as the correct class, and it will work out of the box.

0
source share

All Articles