Hibernate One To One Mapping tutorial

Hibernate One To One Mapping tutorial

This tutorial will show you how to configure hibernate One To One Mapping with MySQL database with project using Maven in eclipse. At the end we will be able to insert and select data from MySQL database.

Hibernate One To One Mapping tutorial – Tools needed:

  • Eclipse ( We are using eclipse Kepler)
  • Install JBoss tools in eclipse. If you are not sure how to install JBoss in eclipse please user this URL:Install JBoss tools in eclipse
  • MySQL data base (Install MySQL Community Server (GPL) version in your system : MySQL Community Server). We are using version 5.6
  • Hibernate 3.2
  • Maven 3.0.4

Hibernate One To One Mapping tutorial – below are steps: 

1. Create table in MySQL data base script:

CREATE TABLE address ( 
	Steet_Name	varchar(50) NULL,
	Location  	varchar(25) NULL,
	City      	varchar(25) NULL,
	Zip       	varchar(25) NULL,
	State     	varchar(25) NULL,
	id        	int(11) NOT NULL DEFAULT '0' ,
    PRIMARY KEY (id)
	)
GO

CREATE TABLE person ( 
	First_Name	varchar(50) NULL,
    Last_Name	varchar(50) NULL,
	id        	int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (id),
    FOREIGN KEY (id)
    REFERENCES address (id)	)

 

2. Eclipse setup:

  • Open your eclipse
  • Create Maven project name: HibernateMySQLTest
  • By default eclipse kepler creates dynamic maven project of version 2.3. If you try to change version to 2.5 through Right click project –>Properties –> Project Facet will give you an error and if you are getting error then click Window –> Show view –> Other –> General –> Navigator –> Click OK
  • Eclipse will change in Navigator perspective. Click .setting folder — and open file name Open org.eclipse.wst.common.project.facet.core.xml file then make change show below:
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <fixed facet="wst.jsdt.web"/>
  <installed facet="java" version="1.5"/>
  <installed facet="jst.web" version="2.5"/>
  <installed facet="wst.jsdt.web" version="1.0"/>
</faceted-project>

 

  • This will change maven dynamic project version 2.5.
  • Now create resources folder inside src/main.
  • Create package com.javahonk and com.javahonk.bean and com.javahonk.util
  • Project structure shown below:

Hibernate One To One Mapping tutorial

3. Hibernate configuration:

4. Create hibernate configuration file:

  • Create file name hibernate.cfg.xml under src/main/resources folder and copy paste below code(Note: Change your MySQL value accordingly) 

<?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">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">admin</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/JavaHonk</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.default_schema">JavaHonk</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="show_sql">true</property>
        <mapping resource="Address.hbm.xml"></mapping>
        <mapping resource="Person.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>

 

5. Add dependency in pom.xml file.

  • Copy paste below pom.xml file to your file:

<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.javahonk</groupId>
  <artifactId>HibernateMySQLTest</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>HibernateMySQLTest Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <!-- MySQL database -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.9</version>
	</dependency>

	<dependency>
		<groupId>org.hibernate</groupId>
		<artifactId>hibernate</artifactId>
		<version>3.2.3.ga</version>
	</dependency>            

	<dependency>
		<groupId>dom4j</groupId>
		<artifactId>dom4j</artifactId>
		<version>1.6.1</version>
	</dependency>

	<dependency>
		<groupId>commons-logging</groupId>
		<artifactId>commons-logging</artifactId>
		<version>1.1.1</version>
	</dependency>

	<dependency>
		<groupId>commons-collections</groupId>
		<artifactId>commons-collections</artifactId>
		<version>3.2.1</version>
	</dependency>

	<dependency>
		<groupId>cglib</groupId>
		<artifactId>cglib</artifactId>
		<version>2.2</version>
	</dependency>

	<dependency>
		<groupId>javax.transaction</groupId>
		<artifactId>jta</artifactId>
		<version>1.1</version>
	</dependency>

	<dependency>
		<groupId>asm</groupId>
		<artifactId>asm</artifactId>
		<version>3.1</version>
	</dependency>

  </dependencies>
  <build>
    <finalName>HibernateMySQLTest</finalName>
  </build>
</project>

 

6. Create mapping file

  • Create mapping file name: Address.hbm.xml inside src/main/resources folder and copy paste below code:
<?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 Feb 21, 2014 5:31:02 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.javahonk.bean.Address" table="address">
        <id name="id" type="int">
            <column name="id" />
            <generator class="increment" />
        </id>
        <property name="steetName" type="string">
            <column name="Steet_Name" length="50" />
        </property>
        <property name="location" type="string">
            <column name="Location" length="25" />
        </property>
        <property name="city" type="string">
            <column name="City" length="25" />
        </property>
        <property name="zip" type="string">
            <column name="Zip" length="25" />
        </property>
        <property name="state" type="string">
            <column name="State" length="25" />
        </property>

        <one-to-one name="person" class="com.javahonk.bean.Person"
            cascade="save-update"></one-to-one>

    </class>
</hibernate-mapping>

 

  • Create mapping file name: Person.hbm.xml inside src/main/resources folder and copy paste below code:
<?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 Feb 21, 2014 5:31:02 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.javahonk.bean.Person" table="person">
        <id name="id" type="int">
            <column name="id" />
            <generator class="foreign">
                <param name="property">address</param>
            </generator>
        </id>
        <property name="firstName" type="string">
            <column name="First_Name" length="50" />
        </property>
        <property name="lastName" type="string">
            <column name="Last_Name" length="50" />
        </property>

        <one-to-one name="address" class="com.javahonk.bean.Address"
            cascade="save-update"></one-to-one>

    </class>
</hibernate-mapping>

 

Hibernate One To One Mapping tutorial Note: Please take look at both mapping file we have created one-to-one tag which creates relation between Address and Person. As also see in the data base table we have created two table person and address where person has Foreign key reference from table address. Also see below tag

in Address.hbm.xml where we are using class increment which will increase id value of address table automatically and we don’t need to set it explicitly during insertion data to the table and because we have one-to-one reference to the person table so data will be inserted in address table first then hibernate will look for id and update this to the person table and copy whatever data we set from our main class.

7. Create model class

  • Create model class name: Address.java inside package com.javahonk.bean and copy paste below code:
package com.javahonk.bean;
// default package
// Generated Feb 21, 2014 5:31:02 PM by Hibernate Tools 3.4.0.CR1

/**
 * Address generated by hbm2java
 */
public class Address implements java.io.Serializable {

	private int id;
	private String steetName;
	private String location;
	private String city;
	private String zip;
	private String state;

	private Person person;

	public Address() {
	}

	public Address(int id) {
		this.id = id;
	}

	public Address(int id, String steetName, String location, String city,
			String zip, String state) {
		this.id = id;
		this.steetName = steetName;
		this.location = location;
		this.city = city;
		this.zip = zip;
		this.state = state;
	}

	public int getId() {
		return this.id;
	}

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

	public String getSteetName() {
		return this.steetName;
	}

	public void setSteetName(String steetName) {
		this.steetName = steetName;
	}

	public String getLocation() {
		return this.location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	public String getCity() {
		return this.city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getZip() {
		return this.zip;
	}

	public void setZip(String zip) {
		this.zip = zip;
	}

	public String getState() {
		return this.state;
	}

	public void setState(String state) {
		this.state = state;
	}

	/**
	 * @return the person
	 */
	public Person getPerson() {
		return person;
	}

	/**
	 * @param person the person to set
	 */
	public void setPerson(Person person) {
		this.person = person;
	}

}

 

  • Create model class name: Person.java inside package com.javahonk.bean and copy paste below code:

package com.javahonk.bean;
// default package
// Generated Feb 21, 2014 5:31:02 PM by Hibernate Tools 3.4.0.CR1

/**
 * Person generated by hbm2java
 */
public class Person implements java.io.Serializable {

	private int id;
	private String firstName;
	private String lastName;

	private Address address;

	public Person() {
	}

	public Person(int id) {
		this.id = id;
	}

	public Person(int id, String firstName, String lastName) {
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public int getId() {
		return this.id;
	}

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

	public String getFirstName() {
		return this.firstName;
	}

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

	public String getLastName() {
		return this.lastName;
	}

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

	/**
	 * @return the address
	 */
	public Address getAddress() {
		return address;
	}

	/**
	 * @param address the address to set
	 */
	public void setAddress(Address address) {
		this.address = address;
	}

}

 

8. Create utility class

  • Create util class name HibernateUtil.java inside com.javahonk.util package and copy paste below code:
package com.javahonk.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {
		try {
			return new Configuration().configure().buildSessionFactory();
		} catch (Throwable ex) {
			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();
	}
}

 

9. Create main class

  • Finally create main class which is java main class. We will use this class to insert and select data from table. Create class name OneToOneInsert.java inside package com.javahonk and copy paste below code in it:

package com.javahonk;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.javahonk.bean.Address;
import com.javahonk.bean.Person;
import com.javahonk.util.HibernateUtil;

public class OneToOneInsert {

	public static void main(String[] args) {

		SessionFactory sf = HibernateUtil.getSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();

        Address address=new Address();
		address.setSteetName("Main St."); 
		address.setLocation("APT 55");
		address.setCity("Edison");
		address.setZip("10038");
		address.setState("NJ");	

        Person person=new Person();
        person.setFirstName("First name");
        person.setLastName("Last name");

        address.setPerson(person);
        person.setAddress(address);

        session.save(address); 

        List<Address> address3 = session.createQuery("from Address").list();
        for (Address address2 : address3) {
            System.out.println("Address table data:");
            System.out.println("Stree Name: "+address2.getSteetName()+" Location: "+address2.getLocation()+" City: "+address2.getCity()+" State: "+address2.getState()+" Zip: "+address2.getZip());
            System.out.println("Person table data:");
            System.out.println("First Name: "+address2.getPerson().getFirstName()+" Last name: "+address2.getPerson().getLastName()+"\n");
        }

        session.getTransaction().commit();
        session.close();

	}

}

 

  • Hibernate one to one mapping tutorial : We are all set to run our code. Before run refresh and clean your project. Right click InsertData.java class –> Run As –> Java Application
  • You will see on console it has inserted data to table name address and person and selected data from the table that also show on console as below:

Hibernate One To One Mapping tutorial

 

  • That’s it. Hibernate One To One Mapping tutorial .

download2 Download project: HibernateMySQLTest

Leave a Reply

Your email address will not be published. Required fields are marked *