Hibernate (4.x) + MySQL (XML Configuration)

Environment

  • Eclipse Indigo Release
  • mySql 5.x

Library

( 1 ) MySQL Database Settings

CREATE TABLE IF NOT EXISTS persons (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(50) NOT NULL,
  PRIMARY KEY ('id')
)

( 2 )  Create Java Project

( 3 ) Copy Jar files

  • Unpack hibernate.zip got lib\required copy all jars to the project lib folder
  • Copy mysql-connector-java to lib folder
  • Add all jars to the project build path

( 4 ) Java Files (Person.java + HibernateSessionFactory.java)

Person.java -> plain java class

package com.hmkcode.vo;

public class Person {

	private int id;
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

}

HibernateSessionFactory.java -> create the connection

package com.hmkcode.hibernate;

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

public class HibernateSessionFactory {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
        	Configuration configuration = new Configuration();
            configuration.configure();
            ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();        
            return configuration.buildSessionFactory(serviceRegistry);
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

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

}

( 5 ) XML Files (Person.hbm.xml + hibernate.cfg.xml)

Person.hbm.xml – > map database table (persons) to java class (Person.java)

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.hmkcode.vo.Person" table="persons" catalog="hmkcode">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="name" type="string">
            <column name="name" length="50" not-null="true" unique="true" />
        </property>

    </class>
</hibernate-mapping>

hibernate.cfg.xml – > database configuration

<?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="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hmkcode</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password"></property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <mapping resource="./com/hmkcode/hibernate/xml/mapping/Person.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>

( 6 ) Where to Place each File

( 7 ) Test App

Main.java -> run the application

package com.hmkcode;

import org.hibernate.Session;

import com.hmkcode.hibernate.HibernateSessionFactory;
import com.hmkcode.vo.Person;

public class Main 
{
    public static void main( String[] args )
    {
        System.out.println("Hibernate + MySQL");
        Session session = HibernateSessionFactory.getSessionFactory().openSession();

        session.beginTransaction();
        Person person = new Person();

        person.setName("HMK");

        session.save(person);
        session.getTransaction().commit();
    }
}

Result:

Download Source Code: hibernate-mysql.zip

One thought on “Hibernate (4.x) + MySQL (XML Configuration)

Comments are closed.