hibernate enum mapping example

 * Male or Female. Used to customize Account messages (e.g. he or she usage) and
 * to choose the default profile picture.
public enum Gender {
    Male, Female;
User Domain:
public class User {

    private String firstName;
    private String lastName;
    private Gender gender;
    private String email

     * Gets the <code>User</code>'s firstName
     * @return the firstName
    public String getFirstName() {
        return firstName;

     * Sets the <code>User</code>'s firstName
     * @param firstName the firstName to set
    public void setFirstName(String firstName) {
        this.firstName = firstName;

     * Gets the <code>User</code>'s lastName
     * @return the lastName
    public String getLastName() {
        return lastName;

     * Sets the <code>User</code>'s lastName
     * @param lastName the lastName to set
    public void setLastName(String lastName) {
        this.lastName = lastName;

     * Gets the <code>User</code>'s email
     * @return the email
    public String getEmail() {
        return email;

     * Sets the <code>User</code>'s email
     * @param email the email to set
    public void setEmail(String email) {
        this.email = email;
Hibernate Mapping (HBM):
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

  <class table="user" name="com.javachap.domain.user.User">

    <id name="uid" column="usr_uid">
      <generator class="increment"/>

    <property name="firstName" type="java.lang.String" column="usr_first_name"/>

    <property name="lastName" type="java.lang.String" column="usr_last_name" />

    <property name="gender" column="usr_gender" not-null="true">
	  <type name="org.hibernate.type.EnumType">
         <param name="enumClass">com.javaachap.domain.user.Gender</param>
         <param name="type">12</param>

    <property name="email" type="java.lang.String" column="usr_email"/>


By default Hibernate persists the enumeration value as integer in the database when type param is not specified, In order to store the enum display name, we use a param type, which should be pointed to value in java.sql.Types. Since we want to store the enum display name in database we have mapped it to 12 which is equivalent to java.sql.Types.VARCHAR.

Hibernate Annotation Based Mapping:

If you prefer convention over configuration, below is the way to map an enum using annotation.

public class User {

   Gender gender




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s