GeeCON Prague 2014*
The moose likes Object Relational Mapping and the fly likes How to insert enum type entity in MySQL with JPA Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "How to insert enum type entity in MySQL with JPA" Watch "How to insert enum type entity in MySQL with JPA" New topic
Author

How to insert enum type entity in MySQL with JPA

Jack Bush
Ranch Hand

Joined: Oct 20, 2006
Posts: 235
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

Joined: Oct 01, 2007
Posts: 553
Use, @Enumerated(EnumType.STRING)

See,

http://en.wikibooks.org/wiki/Java_Persistence/Basic_Attributes#Enums


TopLink : EclipseLink : Book:Java Persistence : Blog:Java Persistence Performance
Karsten Wutzke
Ranch Hand

Joined: Jul 20, 2010
Posts: 106

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


OCJP JavaSE 6 (86%)
Jack Bush
Ranch Hand

Joined: Oct 20, 2006
Posts: 235
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: 553
Use Enum.valueOf(Color.class, text) to convert a String to an enum.
Jack Bush
Ranch Hand

Joined: Oct 20, 2006
Posts: 235
Hi James,

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

Thank you very much,

Jack
 
GeeCON Prague 2014
 
subject: How to insert enum type entity in MySQL with JPA