Hibernate 4 Example (XML Mapping Style)


This is a quick guide to create hibernate project using hibernate xml mapping, in this example we use following tools

– Eclispe Kepler
– maven
– h2 database
– hibernate tools (eclipse plugin from jboss.org)

Install Hibernate Tools
first we need to install hibernate tools for eclipse using update site.

http://download.jboss.org/jbosstools/updates/stable/kepler/

in eclispe goto menu Help->Install new Software…
insert http://download.jboss.org/jbosstools/updates/stable/kepler/ to work with
and filter hibernate
then select Hibernate Tools and JBoss Maven Hibernate Configurator which showed in following image.

Hibernate Tools

click next to proceed. Once the installation is finished, eclispe will prompt to restart.

Create Maven Project
open menu File->New->Other…

Create Project
select Maven Project and Click Next button.

Create Project
Checked Create a Simple Project(skip archetype selection) and Click Next.

Create Project

add project detail
Group Id : com.mockupcode.example.hibernate
Artifact Id : xmlmapping
Click finish to complete create project.

Project Structure
Show project Structure.

Add maven dependency
At this step, we need to add 2 maven dependency hibernate and h2 in pom.xml showed bellowed.

<dependency>
	<groupId>org.hibernate</groupId>
	<artifactId>hibernate-core</artifactId>
	<version>4.2.3.Final</version>
</dependency>
<dependency>
	<groupId>com.h2database</groupId>
	<artifactId>h2</artifactId>
	<version>1.3.173</version>
</dependency>

complete pom.xml after add dependency.

<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>com.mockupcode.example.hibernate</groupId>
	<artifactId>xmlmapping</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.2.3.Final</version>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<version>1.3.173</version>
		</dependency>
	</dependencies>
</project>

Create Hibernate Config
Hibernate Config
Right click on src/main/resource select New->Other…

Hibernate Config
In Select a wizard select Hibernate->Hibernate Configuration File (cfg.xml) Click Next.

Hibernate Config
In configuration, make sure it is everything is same as image above, then click finish

add property to hibernate.cfg.xml

<property name="hibernate.hbm2ddl.auto">update</property>

complete hibernate.cfg.xml

<?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.connection.driver_class">org.h2.Driver</property>
        <property name="hibernate.connection.password">sa</property>
        <property name="hibernate.connection.url">jdbc:h2:~/test</property>
        <property name="hibernate.connection.username">sa</property>
        <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
    </session-factory>
</hibernate-configuration>

Create Bean
Create Test.java in package com.mockupcode.example.hibernate.xmlmapping.model

package com.mockupcode.example.hibernate.xmlmapping.model;

import java.io.Serializable;

public class Test implements Serializable {
	private long id;
	private String name;
	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;
	}	
}

Create Hibernate Mapping file
Right click project select New->Other…->Hibernate->Hibernate Xml Mapping File(hbm.xml).
Wizard will generate file Test.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Aug 2, 2013 2:21:57 AM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.mockupcode.example.hibernate.xmlmapping.model.Test" table="TEST">
        <id name="id" type="long">
            <column name="ID" />
            <generator class="identity" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
    </class>
</hibernate-mapping>

add mapping file to hibernate.cfg.xml

<?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.connection.driver_class">org.h2.Driver</property>
  <property name="hibernate.connection.password">sa</property>
  <property name="hibernate.connection.url">jdbc:h2:~/test</property>
  <property name="hibernate.connection.username">sa</property>
  <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
  <property name="hibernate.hbm2ddl.auto">create-drop</property>
  <mapping resource="com/mockupcode/example/hibernate/xmlmapping/model/Test.hbm.xml"/>
 </session-factory>
</hibernate-configuration>

Create Code Insert data

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

import com.mockupcode.example.hibernate.xmlmapping.model.Test;


public class App {
	private static final SessionFactory ourSessionFactory;
    private static final ServiceRegistry serviceRegistry;

    static {
        try {
            Configuration configuration = new Configuration();
            configuration.configure();

            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            ourSessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static Session getSession() throws HibernateException {
        return ourSessionFactory.openSession();
    }
    
    public static void main(String[] args){
	Transaction tx = null;
	try {
		tx = getSession().beginTransaction();
		Test test = new Test();
		test.setName("my test");
		getSession().save(test);
		tx.commit();
		System.out.println("get ID from detached bean : "+test.getId());
	} catch (Exception ex) {
		if(tx!=null)tx.rollback();
	}finally{
		getSession().close();
	}
    }
}

run App.java log will show.

INFO: HHH000126: Indexes: [primary_key_1]
Aug 02, 2013 3:16:21 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate: insert into TEST (ID, NAME) values (null, ?)
get ID from detached bean : 1

Download Source From : Github



me on google plus+Jirawong Wongdokpuang

Advertisements

3 thoughts on “Hibernate 4 Example (XML Mapping Style)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s