Wednesday, December 28, 2011

Open Session In View Filter Usage

Open Session In View Filter of Spring framework takes care of hibernate session management of a web application.  The integration of it is done at the web.xml.

Firstly, the spring beans ought to be loaded to the application context. This is done with a 'context-param' element. Secondly, define a filter with a 'filter' element (here my filter class is com.shyarmal.filter.MyOpenSessionInViewFilter which extends org.springframework.orm.hibernate3.support.OpenSessionInViewFilter).  Thirdly, define a filter mapping to the filter appropriately using 'filter-mapping' element. Notice the init parameter (sessionFactoryBeanName) passed to the filter. It is the id of the session factory defined in spring beans xml configurations.

web.xml elements of interest are as follows.
===================================================================
<context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/springmvc-servlet.xml</param-value>
</context-param>

<filter>
   <filter-name>openSessionInViewFilter</filter-name>
   <filter-class>com.shyarmal.filter.MyOpenSessionInViewFilter</filter-class>
   <init-param>
        <param-name>sessionFactoryBeanName</param-name>
        <param-value>sessionFactory</param-value>
   </init-param>
</filter>

<filter-mapping>
        <filter-name>openSessionInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>
===================================================================

Following are the spring bean definitions related to session factory used for the integration of open session in view filter.
===================================================================

<bean id="hibernateConfigProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
   <property name="location">
       <value>classpath:hibernate.properties</value>
   </property>
</bean>

<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
   <property name="driverClassName" value="${jdbc.driver.class.name}"/>
   <property name="url" value="${jdbc.url}"/>
   <property name="username" value="${jdbc.username}"/>
   <property name="password" value="${jdbc.password}"/>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="mappingResources">
        <list>
            <value>Accounts.hbm.xml</value>
             .....
            .....
            .....
        </list>
    </property>
    <property name="hibernateProperties" ref="hibernateConfigProperties"/>
</bean>

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

thanks,
Shyarmal.

Sunday, December 11, 2011

Read and display image - Java Swing


package com.shyarmal.image.display;

import java.awt.Color;
import java.awt.Image;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.border.LineBorder;

/**
 *
 * @author  shyarmal
 * An external image file is read, re-sized and rendered in a
 * JLabel.
 */
public class ImageForm extends extends javax.swing.JFrame {

    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;


/**
This is the default constructor of the JFrame. This can not be used to render an image. Basically the initialization of components are done here. 
*/
    public ImageForm() {
        initComponents();
        this.setLocation(100, 150);
        jLabel1.setBorder(new LineBorder(Color.DARK_GRAY, 5));
        this.setResizable(false);
    }


/**
This is the constructor to be used to set an image. Path of the image file is passed as an argument, which is used to get an image icon from the method, createImageIcon(path) below. The image icon is set to the JLabel. Further the tile of the JFrame is set here. The default constructor is called first to initialize the components of the JFrame.
*/
    public ImageForm(String path) {
        this();
        this.setTitle("Image: " + path.substring(
                           path.lastIndexOf("\\") + 1));
        jLabel1.setIcon(createImageIcon(path));
//        jLabel1.setIcon(new ImageIcon(readFile(path)));
        getContentPane().add(jLabel1);
    }
/**
CREATING AND RESCALING OF AN IMAGE
An image is created from the byte data obtained by reading the image file (refer to the method, readImageFile(String path)). The image created is rescaled to the dimensions of the label in which it is to be rendered. An image icon is created from the rescaled image and returned.
*/
    private ImageIcon createImageIcon(String path) {
        Image image = new ImageIcon(
                readImageFile(path)).getImage();
        Image rescaledImage = image.getScaledInstance(
               jLabel1.getWidth(), jLabel1.getHeight(),
                      Image.SCALE_DEFAULT);
        return new ImageIcon(rescaledImage);
    }


/**
READING IMAGE DATA FROM (EXTERNAL) FILE
File path is passed into this method and a file input stream is created using the same. Length of byte data available in the input stream is obtained [fis.available()]. A byte array of the length, determined by this means is subsequently created. All the data is read into the byte array from the input stream [while ((i = fis.read(data)) != -1);] and returned.
*/
    private byte[] readImageFile(String path) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(path);
            int length = fis.available();
            byte[] data = new byte[length];
            int i = 0;
            while ((i = fis.read(data)) != -1);
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }               
   
    //  auto generated codes for the JFrame are not shown.              
}




thanks,
Shyarmal.

Detached Criteria - Hibernate

The following is an example usage of DetachedCriteria in hibernate. CoinTrxLedger is the domain class which is to be queried and it consists of a set of CoinBuckets. Detached Criteria is used to prepare a sub-query using CoinBuckets (which is not the main query class).
CoinTrxLedger entities are to be selected, which are having CoinBucket entities having the CoinBucket.PROPERTY_ACCOUNT set to An entity, account (passed in to the method).

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

    public List<CoinTrxLedger> getTransactionEntries(Account account) {
        Session session = getSessionFactory().getCurrentSession();
        Criteria criteria = session.createCriteria(CoinTrxLedger.class);
        DetachedCriteria dCriteria = DetachedCriteria.forClass(CoinBucket.class);
        dCriteria.add(Restrictions.eq(CoinBucket.PROPERTY_ACCOUNT, account));
        dCriteria.setProjection(Projections.property(CoinBucket.PROPERTY_ID));
        criteria.add(Subqueries.propertyEq(CoinTrxLedger.PROPERTY_COIN_BUCKET, dCriteria));
        return criteria.list();
    }

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

Create a criteria of the query entity;
          Criteria criteria = session.createCriteria(CoinTrxLedger.class);

Create the sub-query, define restrictions and projections as required:
         DetachedCriteria dCriteria = DetachedCriteria.forClass(CoinBucket.class);
     dCriteria.add(

Restrictions.eq(CoinBucket.PROPERTY_ACCOUNT, account));
     dCriteria.setProjection(Projections

.property(CoinBucket.PROPERTY_ID));

Add the sub-query to the main criteria:
        criteria.add(
Subqueries.propertyEq(CoinTrxLedger.PROPERTY_COIN_BUCKET, dCriteria));

thanks,
Shyarmal

Wednesday, October 5, 2011

Scalaquery Example

This is an example of scalaquery. Some save, update and find queries can be found at the end of the post. First of all the table structure should be created in scalaquery to create the table as desired in whatever the database.
Let's have a look at the model of the table. This table does not consist of any primary or foreign key constraints. The object, MoMessageHistory will map to a table by the name "mo_message_history" in the database.

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

object MoMessageHistory extends Table[(String, String, String, Long, String)]("mo_message_history") {
  def correlationId = column[String]("correlation_id", O NotNull, O DBType "VARCHAR(60)")
  def text = column[String]("text", O NotNull)
  def timestamp = column[Long]("time_stamp", O NotNull, O DBType "BIGINT(15)")
  def validity = column[String]("validity", O NotNull, O DBType "VARCHAR(20)")
  def msisdn = column[String]("msisdn", O NotNull, O DBType "VARCHAR(15)")
  def * = correlationId ~ msisdn ~ text ~ timestamp ~ validity
}

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

The object, MoMessageHistory extends Table which generalizes with scala data types (the data types within square brackets and then parentheses in the first line). These data types are those of attributes of MoMessageHistory. "def * = correlationId ~ msisdn ~ text ~ timestamp ~ validity" projects the columns so that they'll be available for the queries. The number of columns projected and the data types of the same should exactly match the data types of the first line and should also be in the same order.

Now let's explore the line,
def correlationId = column[String]("correlation_id", O NotNull, O DBType "VARCHAR(60)")
Here the attribute of MoMessageHistory, correlationId which is of type String of scala will map to the column, "correlation_id" in the database table mo_message_history. The column, correlation_id can not be null and is of the database data type, varchar(60).

Below is a save query. The method insert is called on MoMessageHistory. The data to be saved should be given in the order of the projection (as discussed above) at the table creation.

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

def save(correlationId:String,msisdn: String, text: String, validity: String) = {
        MoMessageHistory insert (correlationId, msisdn, text,     System.currentTimeMillis().asInstanceOf[Long], validity)
}

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

The following code returns a list of records from the database by msisdn, a field of MoMessasgeHistory. Here the list returned is made of tuples (List[(String, String, String, Long, String)]). 
"MoMessageHistory where {_.msisdn === msisdn}" generates a scalaquery 'Query'. the 'list' method called on it will return the desired results.
===================================================================

def find(msisdn: String): List[(String, String, String, Long, String)] = {
   val q = MoMessageHistory where {_.msisdn === msisdn}
    println("find query: \n" + q.selectStatement)
   q.list
}

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

This query also uses a where clause like the above, except for the fact it has 3 selection criteria.  Attributes of the MoMessageHistory are referred using _.
===================================================================

def find(msisdn: String, from: java.util.Date, to: java.util.Date): List[(String, String, String, Long, String)] = {
   val q = MoMessageHistory where {_.msisdn === msisdn} where {_.timestamp <= to.getTime} where  {_.timestamp >= from.getTime}
   println("find query: \n" + q.selectStatement)
  q.list
}

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

The query below updates the validity field of tuples with a siven id. First a query is generated to select the effecting records. Then updating is done on the same.
===================================================================

def updateValidity(id:String , validity:String)={
  val q1 = for (msg <- MoMessageHistory if msg.correlationId === id)
  yield msg.validity

  if (!q1.list.isEmpty) {
    println("found item " + id +validity)
    q1 update (validity)
    printf("updating list %s", q1.list)

  }

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

The query,
'val q1 = for (msg <- MoMessageHistory if msg.correlationId === id)
yield msg.validity'
is similar to the sql query, 
'select msg.validity from mo_message_history where msg.correlationId=<the id>'

If the query yields any results, It is updated with the validity parameter passed into the method.
'q1 update (validity)'


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


thanks,
Shyarmal

Saturday, September 17, 2011

Hibernate with JPA Annotations - OneToOne

 This example illustrates a one-to-one mapping in Hibernate using JPA annotations. The illustration is about a case where a driver has one driving license. Here the license details will be saved to a database table by the name 'license' and that of driver to 'driver'. I'm only discussing the OneToOne mapping here. [For other basic information, refer to Hinernate Annotations Example].
  The mappings of the classes should be in the hibernate.cfg.xml file
        <mapping class="com.shyarmal.hibernate.Driver"/>
        <mapping class="com.shyarmal.hibernate.License"/>

My License class.
===============================================================

package com.shyarmal.hibernate;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "license")
public class License {

    private Long id;
    private Date issueDate;
    private String country;
    private String category;

    private License() {
    }
   
    public License(Date issueDate, String country, String category) {
        this.issueDate = issueDate;
        this.country = country;
        this.category = category;
    }

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

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

    @Column(name = "issue_date", columnDefinition = "timestamp")
    public Date getIssueDate() {
        return issueDate;
    }

    public void setIssueDate(Date issueDate) {
        this.issueDate = issueDate;
    }

    @Column(name = "country")
    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Column(name = "category")
    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }
}
===============================================================

The Driver class should have an instance of the License class, if to form a one-to-one.
My Driver class
===============================================================

package com.shyarmal.hibernate;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "driver")
public class Driver {

    private Long id;
    private String name;
    private int age;
    private License license;

    private Driver() {
       
    }
   
    public Driver(String name, int age) {
        this.name = name;
        this.age = age;
    }
   
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @OneToOne(cascade = CascadeType.ALL)
    public License getLicense() {
        return license;
    }

    public void setLicense(License license) {
        this.license = license;
    }

}

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

@OneToOne:- This annotation is to make the link between the corresponding field of the annotated class to that intended to be related in one-to-one mapping. The CascadeType is set to ALL which will reflect any change in the 'driver' table to the 'license' table. That means, for an instance if a driver is deleted his license will also be deleted correspondingly.


thanks,
Shyarmal.

Thursday, September 15, 2011

Loop Break - Scala

Following example shows how to break out of a loop in Scala. Here the package, 'util.control.Breaks._' is imported and the foreach loop is enclosed in a 'breakable' block (to avoid a runtime exception caused by the break). In the example the loops breaks when n is 5.

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

package shyarmal.test.scala

import util.control.Breaks._

object ScalaBreak {

  def main(args: Array[String]) {

    val nums = 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 7 :: Nil
    breakable {
      nums.foreach(n => {
        if (n == 5)
          break
        println(n)
      })
    }

  }
}

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

The output: 1 2 3 4

thanks,
Shyarmal

Saturday, August 27, 2011

Hibernate Annotations with Collections (List)

Following class illustrates how to model a java.util.List in hibernate with annotations. The subjects that a student takes are given in a list. So the 'Student' class is having an instance of List of String's. This can only be used to model collections of Java built-in types.
 
package com.shyarmal.hibernate;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;

@Entity
public class Student {

    private Long id;
    private String college;
    private List<String> subjects;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }
   
    public void setId(Long id) {
        this.id = id;
    }

    @Column(name = "college")
    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }
   
    @ElementCollection(fetch = FetchType.LAZY)
    @JoinTable(name = "student_subjects",
       joinColumns = {@JoinColumn(name = "student_id")})
    public List<String> getSubjects() {
        return subjects;
    }

    public void setSubjects(List<String> subjects) {
        this.subjects = subjects;
    }
}


Annotations used to handle the scenario;
  • @ElementCollection:- Informs that the instance annotated should be considered as a Java collection type. The optional attribute 'fetch' may be given to stress how the collection should be loaded [either lazy (the default) or eager]
  • @JoinTable:- Used to explicitly specify the properties of the table which joins the collection data with the entity in concern. Name of the joining column also can be given, which links to the primary key of the entity. Inverse joining column attribute should not be specified in this case.

thanks,
Shyarmal.

Hibernate Inheritance with Annotations

 There are a few approaches to deal with inheritance in hibernate. The technique discussed in this post accommodates all in one table.
  I'm having an abstract class, 'Person' and two of it's subclasses, 'Student' and 'Employee'. Both 'Student' and 'Employee' information is to be stored in a single table, named 'person'.

==================================================================
package com.shyarmal.hibernate;

import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;

@Entity
@Table(name = "person")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "person_type", discriminatorType = DiscriminatorType.STRING)
public abstract class Person {

    private Long id;
    protected String nic;
    protected int age;
    protected String name;
    protected char sex;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }
   
    public void setId(Long id) {
        this.id = id;
    }
   
    @Column(name = "nic", unique = true, nullable =false)
    public String getNic() {
        return nic;
    }

    public void setNic(String nic) {
        this.nic = nic;
    }

    @Column(name = "age")
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Column(name = "name", nullable = false, length = 30)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Column(name = "gender", length = 2, nullable = false)
    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }
}

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

  First, we'll have a look at the 'Person' class. Here I'll only discuss what's done to accomplish inheritance [For other basic information, refer to Hinernate Annotations Example].  The annotation, @Inheritance denotes inheritance and there are subclasses of person to be mapped. Moreover all 'Person' instances will be available in a single database table, since the inheritance strategy used is  'InheritanceType.SINGLE_TABLE'.   
   @DiscriminatorColumn is mandatory in this approach. It forms a new column in the database with the name specified in the 'name' attribute. The discriminator column is used to Identify the type of the record (in our example where a record is of type 'Student' or 'Employee'). The attribute 'discriminatorType' states the type of the discriminator column.
   I have posted my 'Student' and 'Employee' classes below.

=================================================================== 
package com.shyarmal.hibernate;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;

@Entity
@DiscriminatorValue("student")
public class Student extends Person {

    private String college;
    private List<String> subjects;

    @Column(name = "college", nullable = false, columnDefinition = "varchar(20) default 'unknown'")
    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }
   
    @ElementCollection(fetch = FetchType.LAZY)
    @JoinTable(name = "student_subjects", joinColumns = {@JoinColumn(name = "person_id")})
    public List<String> getSubjects() {
        return subjects;
    }

    public void setSubjects(List<String> subjects) {
        this.subjects = subjects;
    }

    @Override
    public String toString() {
        return String.format("student: nic [%s], college [%s], name [%s], age [%d]", nic, college, name, age);
    }
}

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

package com.shyarmal.hibernate;

import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

@Entity
@DiscriminatorValue("employee")
public class Employee extends Person {

    private String company;
    private double salary;

    @Column(name = "company", nullable = false, columnDefinition = "varchar(20) default 'unknown'")
    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    @Column(name = "salary", nullable = false, columnDefinition = "double(8, 2) default '0.0'")
    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return String.format("employee: nic [%s], company [%s], name [%s], age [%d]", nic, company, name, age);
    }
}
===================================================================

@DiscriminatorValue annotation should be present in the subclasses. The discriminator value is what's saved in the discriminator column, which was discussed above [in our example if an employee is saved the discriminator column will have the value 'employee' and for a student the value will be 'student']. Notice 'columnDefinition' attribute in @Column in subclasses. If a column is declared not to be nullable, then a default value for the corresponding field should be given as done in the example. If not hibernate does not create the table. 'Student' class has a list of subjects. The methodology used is described here.

Below is the hibernate.cfg.xml used.
=================================================================== 

<?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">root</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.Person"/>
        <mapping class="com.shyarmal.hibernate.Student"/>
        <mapping class="com.shyarmal.hibernate.Employee"/> 
    </session-factory>
</hibernate-configuration>


thanks,
Shyarmal.

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.