Friday, December 21, 2012

Hibernate 4 simple project example

Tools:
  • Eclipse Juno 4.2
  • Maven Integration for Eclipse plugin (m2e)
  • Hibernate 4.1.9.Final
  • MySQL 5.5

View and download source code:
https://bitbucket.org/kipchakbaev/hibernate4-example


1. In Eclipse create new Maven project. In Maven Archetype selection window choose maven-archetype-quickstart.
Enter archetype parameters. My parameters:
Group Id: kipchakbaev.hibernate
Artifact Id: hibernate4-example
package: kipchakbaev.hibernate

Click Finish.

2. Go to pom.xml and add dependencies:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.1.9.Final</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.22</version>
</dependency>

(it is possible to choose hibernate-entitymanager instead hibernate-core)

pom.xml:

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>kipchakbaev.hibernate</groupId>
  <artifactId>hibernate4-example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>hibernate4-example</name>
  <url>http://maven.apache.org</url>

  <properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

   <dependencies>
        <dependency>
    <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
    <version>4.1.9.Final</version>
       </dependency>
       <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.22</version>
       </dependency>
   </dependencies>
</project>

3. In MySQL create schema hibernatedb. Create table customer:

DROP TABLE IF EXISTS customer;
CREATE TABLE customer(
  id INT NOT NULL AUTO_INCREMENT,
  first_name VARCHAR(20) NOT NULL,
  last_name VARCHAR(30) NOT NULL,
  PRIMARY KEY (id)
)

4. In eclipse create folder src/main/resources/:
In your project choose folder src/main/ - right click - new - folder. Folder name: resources.
Right click on resources/ - Build Path - Use as source folder.

5. In src/main/resources/ create folder structure /kipchakbaev/hibernate/common/
In common/ folder create file customer.hbm.xml:


<?xml version='1.0'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="kipchakbaev.hibernate.common.Customer" table="customer" catalog="hibernatedb">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="identity" />
        </id>
        <property name="firstName" type="string">
            <column name="FIRST_NAME" length="20" not-null="true" />
        </property>
        <property name="lastName" type="string">
            <column name="LAST_NAME" length="30" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

6. Create kipchakbaev.hibernate.common package and put Customer.java in it:

package kipchakbaev.hibernate.common;

public class Customer {

private Integer id;
private String firstName;
private String lastName;

public Customer() {
}

public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

public Integer getId() {
return id;
}

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

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}
}

7. In src/main/resources/ create file hibernate.cfg.xml, replace MySQL username and password to yours:


<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatedb</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <mapping resource="kipchakbaev/hibernate/common/customer.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>


8. Create kipchakbaev.hibernate.persistence package and put HibernateUtil.java in it:


package kipchakbaev.hibernate.persistence;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
   
    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    static
    {
        try
        {
            Configuration configuration = new Configuration().configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        }
        catch (HibernateException he)
        {
            System.err.println("Error creating Session: " + he);
            throw new ExceptionInInitializerError(he);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
    // Close caches and connection pools
    getSessionFactory().close();
    }
}


9. Change App.java in package kipchakbaev.hibernate, generated by Maven:

package kipchakbaev.hibernate;

import kipchakbaev.hibernate.common.Customer;
import kipchakbaev.hibernate.persistence.HibernateUtil;
import org.hibernate.Session;

/**
 * Hello hibernate 4!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        System.out.println("Hibernate 4 example");
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Customer customer = new Customer();
        customer.setFirstName("John");
        customer.setLastName("Doe");
        session.save(customer);
        session.getTransaction().commit();
    }
}

Review project structure:






























Run App.java! If successful, you can see last line in eclipse console:

Hibernate: insert into hibernatedb.customer (FIRST_NAME, LAST_NAME) values (?, ?)

View and download source code:
https://bitbucket.org/kipchakbaev/hibernate4-example