- Back to Home »
- enums , JPA »
- Saving ENUM values as String in database using JPA
Posted by : Unknown
Sunday, May 1, 2011
First of all nothing very fancy or technical about this post :)
Let's say you have an enum declaration as shown below and you want to store these values as String (not the evil ordinals) in the database:
public enum UserSex { MALE, FEMALE, UNKNOWN }
To save this enum as String in database, the table where this enum is referenced should declare a column of type varchar as shown below:
`user_sex` varchar(255) DEFAULT NULL
The entity (say User) should use this enumeration as shown below:
@Entity @Table(name = "user") public class User { private Integer id; private UserSex userSex; @Id public Integer getId() { return id; } @Enumerated(EnumType.STRING) @Column(name ="user_sex") public UserSex getUserSex() { return userSex; } public void setId(Integer id) { this.id = id; } public void setUserSex(UserSex userSex) { this.userSex = userSex; }
That's all. Now if you want to load all MALE users, you can use this column in JPA queries as
public List<User> getAllMaleUsers() { return entityManager.createQuery( "select user from User as user where user.userSex=:userSex") .setParameter("userSex", UserSex.MALE).getResultList(); }
Please note that this will work only in case you have complete control on the database side, in case the column is declared as integer or varchar having length say 1 then you will have to write your own converter or fall back to evil ordinal().
NOTE: I'm guessing but I'm pretty sure that for using ENUM as String hibernate 3.2+ is required. So if anyone out there is interested in knowing my POM dependencies then here are they (specific to JBOSS AS 5.1.0 deployment)
javaee javaee-api 5 compile javax.persistence ejb3-persistence 1.0 provided org.hibernate hibernate-entitymanager 3.3.1.ga javax.persistence persistence-api jboss jboss-common-core jboss javassist
Nice article , you have indeed covered storing Enum in database in details with sample code and graphics, how about performance of this approach ?
ReplyDeleteJavin
How Garbage collection works in Java
Good informative Post. One question - Won't storing an integer (ordinal value) be better from a database point of view then storing an string? Since string comparison would be slower then numeric right?
ReplyDelete