I would like to find out how to use entityManager.persist() in JPA to insert enum type object with its descriptive name as opposed to the index / positional number. For instance, we have the following enum type:
public enum Color { Blue, Red, Yellow, Green, White, Black };
The data inserted into MySQL is 0, 1, 2, 3, 4, 5 as opposed to Blue, Red, Yellow, Green, White and Black.
I need to use third-party reporting tools and native SQL and would like to use the descriptive name.
ENUM worked with me when I named its elements the same as the enum values, here ENUM('Blue', 'Red', 'Yellow', ...). If you want all uppercase enums in Java with underscores, you need to do so in the DBs column declaration, too.
Karsten
This message was edited 1 time. Last update was at by Karsten Wutzke
OCJP JavaSE 6 (86%)
Jack Bush
Ranch Hand
Joined: Oct 20, 2006
Posts: 210
posted
0
Hi James & Karsten,
Thank you for responding to this threat and the valuable reference material. Nevertheless, the enum type I had in mind was to do with using a pre-defined type such as Color in another class called Definition.java. This class holds all global types for all applications. Below is the scenario I am referring to:
The last line (33) resulted in "inconvertible type, required definition.Color, found java.util.String" compilation error.
How to cast colorElement.getTextNormalize() string to Color object to be persisted as part of Car record in MySQL database? Is this possible to achieve or do I need to define Color in Car entity class instead?
Thanks again,
Jack
James Sutherland
Ranch Hand
Joined: Oct 01, 2007
Posts: 421
posted
0
Use Enum.valueOf(Color.class, text) to convert a String to an enum.
Jack Bush
Ranch Hand
Joined: Oct 20, 2006
Posts: 210
posted
0
Hi James,
Yes, both @Enumerated(EnumType.STRING) & Enum.valueOf(Color.class, text) have worked.
Thank you very much,
Jack
subject: How to insert enum type entity in MySQL with JPA