Thursday, August 25, 2011

Hibernate Annotations Example

This is a simple demonstration of how hibernate annotations (actually JPA) can be used. I have used mysql database in this example. First let's create a maven project with the following command.

mvn archetype:generate --batch-mode -DarchetypeArtifactId=maven-archetype-quickstart -DgroupId=com.shyarmal.hibernate -DartifactId=hibernate-eg

Create a folder named 'resources' in ....../hibernate-eg/src/main. Then create a file with the name hibernate.cfg.xml in it and paste the following xml codes. The file, hibernate.cfg.xml needs to be in the class path for the application to run successfully.

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

<?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.Car"/>
    </session-factory>
</hibernate-configuration>

===================================================================
     A hibernate session factory is configured in hibernate.cfg.xml. connection.url, connection.username and connection.password are your database url, username and password respectively. Since mysql is used the driver class should be 'com.mysql.jdbc.Driver' and the dialect should be 'org.hibernate.dialect.MySQLDialect'.
     The property show_sql is set to true, which means the sql queries executed by hibernate will be shown in the log. Each time the session factory is created, the database schema will be created as the property, hbm2ddl.auto is set as 'create'.
     Further the database connection pool size is 1 and hibernate's automatic session context management is used. However hibernate's default connection pool is not encouraged to be used for production.
     Mapping classes have to be given in the configuration file. In this example only one class is used which is 'com.shyarmal.hibernate.Car'. 

     The class below instantiates a session factory with the above configurations. HibernateUtil is singleton.
===================================================================

package com.shyarmal.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

    private static SessionFactory sessionFactory = buildSessionFactory();
   
    private static SessionFactory buildSessionFactory() {
        return new AnnotationConfiguration().configure().buildSessionFactory();
    }
   
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

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

The class 'Car' is the class which will be modelled to the database. An instance of this class is mapped to one record of database table which models the class.
===================================================================

package com.shyarmal.hibernate;

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

@Entity
@Table(name="cars")
public class Car {

    private Long id;
    private String make;
    private String brand;
    private String model;
    private double capacity;
    private double price;

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

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

    public String getMake() {
        return make;
    }

    public void setMake(String make) {
        this.make = make;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public double getCapacity() {
        return capacity;
    }

    public void setCapacity(double capacity) {
        this.capacity = capacity;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

}

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

Annotations used;
  • @Entity: The class denoted by this will be considered as an entity (which is mapped to a database table)
  • @Table: The properties of the table to be created such as the name can be given here.
  • @Id: The attribute denoted by this will be taken to be the primary key of the record saved in the table.
  • @GeneratedValue: This makes hibernate generate a value for the annotated attribute.
n.b. If the @Table annotation was not present, The name of the table created will be the same as the name of the class. Column names can be explicitly mentioned with @Column attribute. Since it is not done here, the field names of the table will be the same as the field names of the class.

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

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.shyarmal.hibernate.Car;
import com.shyarmal.hibernate.HibernateUtil;

public class Main {

    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction transaction = session.beginTransaction();
        Car car = new Car();
        car.setBrand("Vitz");
        car.setMake("Toyota ");
        car.setModel("2009");
        car.setCapacity(20.4);
        car.setPrice(30000000);
        session.save(car);
        transaction.commit();
    }
}

===================================================================
The main method above creates a hibernate session from the session factory. A transaction is started for the operation. An instance of 'Car' is saved to the session and subsequently committed to the database.

The 'Main' class can be run with the following maven command.
mvn clean compile exec:java -Dexec.mainClass=com.shyarmal.Main

The pom.xml file used is below.
===================================================================

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.shyarmal.hibernate</groupId>
  <artifactId>hibernate-eg</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>hibernate-eg</name>
  <url>http://maven.apache.org</url>
 
  <dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-annotations</artifactId>
        <version>3.5.6-Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate</artifactId>
        <version>3.6.0.Beta2</version>
        <type>pom</type>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.17</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.6.2</version>
    </dependency>
    <dependency>
        <groupId>org.javassist</groupId>
        <artifactId>javassist</artifactId>
        <version>3.15.0-GA</version>
    </dependency>
  </dependencies>
 
</project>

thanks,
Shyarmal.

No comments:

Post a Comment