Saturday, August 27, 2011

Hibernate annotations with enums

    How enums can be dealt using annotations is described here. In the example there are two enums, 'Status' and 'Priority', which are instances of the class, 'Batch'. 'Batch' is a domain class.

===================================================================

package com.shyarmal.hibernate;

public enum Status {

    STARTED, SUSPENDED, FINISHED, ABANDON
}


>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

package com.shyarmal.hibernate;

public enum Priority {

    HIGH, MEDIUM, LOW
}
===================================================================

   'Batch' is annotated as an entity and it's instances will be saved to a table called 'batch' in the database. @Enumerated annotation is used to mark a filed as an enum. Here the EnumType of 'Priority' is ORDINAL and hence an integer will be saved in the database which corresponds to it's actual value. Integers will be assigned to the enum values in the ascending order, starting with 0. As the EnumType of 'Status' is STRING, the values of it will be saved as varchar in the database.
===================================================================

package com.shyarmal.hibernate;

import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "batch")
public class Batch {

    private Long id;
    private Status status;
    private Priority priority;

    @Id
    @GeneratedValue
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Enumerated(value = EnumType.STRING)
    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    @Enumerated(value = EnumType.ORDINAL)
    public Priority getPriority() {
        return priority;
    }

    public void setPriority(Priority priority) {
        this.priority = priority;
    }

    @Override
    public String toString() {
        return String.format("batch: priority [%s], status [%s]", priority.name(), status.name());
    }

}

===================================================================

Following are some CRUD functions performed on 'Batch'.
===================================================================
// saving a batch
private static void save() {
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            Batch batch = new Batch();
            batch.setPriority(Priority.HIGH);
            batch.setStatus(Status.STARTED);
            session.save(batch);
            transaction.commit();
        } catch(Exception e) {
            transaction.rollback();
            e.printStackTrace();
        }
    }
   
// find one batch by the id.
private static void find() {
    Transaction transaction = null;
     try {
         Session session = HibernateUtil.getSessionFactory().getCurrentSession();
         transaction = session.beginTransaction();
         Batch batch = (Batch) session.get(Batch.class, new Long(1)); // batch with the id 1.
         transaction.commit();
     } catch(Exception e) {
         transaction.rollback();
         e.printStackTrace();
     }
}
   
// editing a batch 
private static void edit() {
     Transaction transaction = null;
      try {
         Session session = HibernateUtil.getSessionFactory().getCurrentSession();
         transaction = session.beginTransaction();
         Batch batch = (Batch) session.get(Batch.class, new Long(1));
         batch.setPriority(Priority.LOW);
         batch.setStatus(Status.SUSPENDED);
         transaction.commit();
      } catch(Exception e) {
         transaction.rollback();
         e.printStackTrace();
      }
}
   
// deleting a batch
private static void delete() {
   Transaction transaction = null;
    try {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        transaction = session.beginTransaction();
        session.delete(session.get(Batch.class, new Long(1)));
        transaction.commit();
    } catch(Exception e) {
        transaction.rollback();
        e.printStackTrace();
     }
}

===================================================================

Hibernate configuration file used is below. Notice the mapping, '<mapping class="com.shyarmal.hibernate.Batch"/>'.
===================================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.url">jdbc:mysql://localhost/test</property>
        <property name="connection.username">danuka</property>
        <property name="connection.password">123</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="hbm2ddl.auto">create</property>
        <property name="connection.pool_size">1</property>
        <property name="current_session_context_class">thread</property>
        <mapping class="com.shyarmal.hibernate.Batch"/> 
    </session-factory>
</hibernate-configuration>

===================================================================
A sample record in the database.
mysql> select * from batch;
+----+----------+-------------+
| id | priority | status        |
+----+----------+-------------+
|  1 |        0 | FINISHED   |
+----+----------+-------------+
1 row in set (0.00 sec)


thanks,
Shyarmal.

No comments:

Post a Comment