• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to insert enum type entity in MySQL with JPA

 
Jack Bush
Ranch Hand
Posts: 235
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

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.

Thanks a lot,

Jack
 
James Sutherland
Ranch Hand
Posts: 553
 
Karsten Wutzke
Ranch Hand
Posts: 106
Hibernate MySQL Database Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jack Bush
Ranch Hand
Posts: 235
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 553
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use Enum.valueOf(Color.class, text) to convert a String to an enum.
 
Jack Bush
Ranch Hand
Posts: 235
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi James,

Yes, both @Enumerated(EnumType.STRING) & Enum.valueOf(Color.class, text) have worked.

Thank you very much,

Jack
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic