0
Sponsored Links


Ad by Google
In this post we are going to create a project to implement the step by step one-to-one association example using hbm.xml file. Before that lets have a look at what exactly one-to-one association in RDBMS ? One-to-One association means, Each row of a table is mapped with exactly one and only one row with another table.
For example, we have passport_detail and person table each row of passport_detail table is mapped with exactly one and only one row of person table. One person has only one passport.

In hibernate one-to-one association can be implemented vi two different ways:
  • Primary key associations
  • Unique foreign key associations
In this tutorial we are going to implement 1st approach Unidirectional one-to-one association vi primary key association. For 2nd approach you may follow this tutorial one-to-one association using unique foreign key

OK, lets start our project.

Here is an one-to-one association mapping of person and passport_detail table ER diagram:


Tools and Technologies we are using here:

  • JDK 7
  • Hibernate 4.2.4
  • MySql 5.5
  • Eclipse Juno 4.2
Overview of the Project Structure:


Main Objects of this project are:
  • jar files
  • hibernate.cfg.xml
  • *hbm.xml (mapping files)
  • database

Step 1. Database Script:

CREATE DATABASE `hibernate_tutorial` ;

USE `hibernate_tutorial`;

/*Table structure for table `passport_detail` */

DROP TABLE IF EXISTS `passport_detail`;

CREATE TABLE `passport_detail` (
  `person_id` int(11) NOT NULL,
  `passport_number` varchar(255) DEFAULT NULL,
  `date_of_issue` datetime DEFAULT NULL,
  `date_of_expiry` datetime DEFAULT NULL,
  PRIMARY KEY (`person_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

/*Table structure for table `person` */

DROP TABLE IF EXISTS `person`;

CREATE TABLE `person` (
  `person_id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(255) DEFAULT NULL,
  `last_name` varchar(255) DEFAULT NULL,
  `date_of_birth` datetime DEFAULT NULL,
  PRIMARY KEY (`person_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

Step 2. Create a Java Project:
Go to File Menu then New->Java Project, and provide the name of the project.


Create a lib folder(Optional):
Right click on your project and create a new folder named it as lib,this step is optional this is just to place all the required jar file. You may put all the jar files anywhere in your system's location, In this project we are putting all the jar files in lib folder.

Step 3. Add libraries(jar files) into project's build path:
required jar files:
  • antlr-2.7.7.jar
  • commons-collections-3.2.1.jar
  • dom4j-1.6.1.jar
  • hibernate-commons-annotations-4.0.5.Final.jar
  • hibernate-core-4.2.4.Final.jar
  • hibernate-jpa-2.1-api-1.0.0.Final.jar
  • jandex-1.1.0.Final.jar
  • javassist-3.18.1-GA.jar
  • jboss-logging-3.1.3.GA.jar
  • jboss-transaction-api_1.1_spec-1.0.0.Final.jar
  • mysql-connector-java-5.1.3-rc-bin.jar
Step 4. Create a hibernate.cfg.xml file: In this project we placed hibernate.cfg.xml file inside src folder.


Here is a complete hibernate.cfg.xml file.

<?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>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate_tutorial</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
         
        <!-- MYSQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
  	<property name="hbm2ddl.auto">update</property>
        <mapping resource="com/hibernate/hbm/xmls/Person.hbm.xml"/>
        <mapping resource="com/hibernate/hbm/xmls/PassportDetail.hbm.xml"/>
          
    </session-factory>
</hibernate-configuration>

Step 5. Create Person.hbm.xml file: Create a mapping file for person table.

Here is a complete Person.hbm.xml file

<?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 29 Oct, 2014 8:47:37 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.hibernate.hbm.pojo.Person" table="person">
        <id name="personId" column="person_id">
            <generator class="identity" />
        </id>
        <property name="firstName" column="first_name"/>
        <property name="lastName" column="last_name"/>
        <property name="dateOfBirth" column="date_of_birth" type="java.util.Date"/>
    </class>
</hibernate-mapping>


Step 6. Create PassportDetail.hbm.xml file: Create a mapping file for passport_detail table. It uses special generator class called foreign.

Here is a complete PassportDetail.hbm.xml file

<?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 29 Oct, 2014 8:47:37 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.hibernate.hbm.pojo.PassportDetail" table="passport_detail">
        <id name="personId" type="java.lang.Integer" column ="person_id">
            <generator class="foreign">
            <param name="property">person</param>
        </generator>
        </id>
        <property name="passportNo" type="java.lang.String">
            <column name="passport_number" />
        </property>
        <property name="dateOfIssue" type="java.util.Date">
            <column name="date_of_issue" />
        </property>
        <property name="dateOfExpiry" type="java.util.Date">
            <column name="date_of_expiry" />
        </property>
        <one-to-one name="person" class="com.hibernate.hbm.pojo.Person"/>
    </class>
</hibernate-mapping>

Step 7. Create a Person Pojo class: Person class has all the properties mapped in Person.hbm.xml

Person.java

package com.hibernate.hbm.pojo;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Person {
	
	private Integer personId;
	private String firstName;
	private String lastName;
	private Date dateOfBirth;

	public Integer getPersonId() {
		return personId;
	}

	public void setPersonId(Integer personId) {
		this.personId = personId;
	}

	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;
	}

	public Date getDateOfBirth() {
		return dateOfBirth;
	}

	public void setDateOfBirth(Date dateOfBirth) {
		this.dateOfBirth = dateOfBirth;
	}


	@Override
	public String toString() {
		return "Person [personId=" + personId + ", firstName=" + firstName
				+ ", lastName=" + lastName + ", dateOfBirth=" + 
				new SimpleDateFormat("yyyy-MM-dd").format( dateOfBirth)
				+ "]";
	}

}


Step 8. Create PassportDetail Pojo class: PassportDetail class contains all the properties mapped in PassportDetail.hbm.xml file.

PassportDetail.java

package com.hibernate.hbm.pojo;

import java.text.SimpleDateFormat;
import java.util.Date;

public class PassportDetail {

	private String passportNo;
	private Date dateOfIssue;
	private Date dateOfExpiry;
	private Person person;
	private Integer personId;
	
	public Integer getPersonId() {
		return personId;
	}

	public void setPersonId(Integer personId) {
		this.personId = personId;
	}

	public String getPassportNo() {
		return passportNo;
	}

	public void setPassportNo(String passportNo) {
		this.passportNo = passportNo;
	}

	public Date getDateOfIssue() {
		return dateOfIssue;
	}

	public void setDateOfIssue(Date dateOfIssue) {
		this.dateOfIssue = dateOfIssue;
	}

	public Date getDateOfExpiry() {
		return dateOfExpiry;
	}

	public void setDateOfExpiry(Date dateOfExpiry) {
		this.dateOfExpiry = dateOfExpiry;
	}

	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	@Override
	public String toString() {
		return "PassportDetail [passportNo="
				+ passportNo + ", dateOfIssue=" + 
				new SimpleDateFormat("yyyy-MM-dd").format(dateOfIssue)
				+ ", dateOfExpiry=" + 
				new SimpleDateFormat("yyyy-MM-dd").format(dateOfExpiry) + 
				", person=" + person + "]";
	}
	
}



Step 9. Create a HibernateUtility class: HibernateUtility class to build SessionFactory vi loading Configuration.

HibernateUtility .java

package com.hbm.util;

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

public class HibernateUtility {
  private static final SessionFactory sessionFactory = buildSessionFactory();
     private static SessionFactory buildSessionFactory() {
     
      Configuration configuration = new Configuration();
      configuration.configure();

      ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().
      applySettings(configuration.getProperties()).buildServiceRegistry();
      SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
   return sessionFactory;
     }
   
     public static SessionFactory getSessionFactory() {
         return sessionFactory;
     }
}

Step 10. Create PersonDAO class: PersonDAO class to perform insert/update/get/delete records into database.

PersonDAO.java

package com.hibernate.hbm.dao;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.hibernate.hbm.pojo.Person;
import com.hibernate.hbm.util.HibernateUtility;

public class PersonDAO {
	private static SessionFactory sessionFactory;
	static {
		sessionFactory = HibernateUtility.getSessionFactory();
	}

	public static Person findById(int id) {
		Session session = sessionFactory.openSession();
		Person person = (Person) session.get(Person.class, id);
		return person;
	}
	
	public static Person save(Person person) {
		Session session = sessionFactory.openSession();

		session.beginTransaction();

		session.save(person);

		session.getTransaction().commit();

		return person;
	}

	public static Person update(Person person) {
		Session session = sessionFactory.openSession();

		session.beginTransaction();

		session.merge(person);

		session.getTransaction().commit();

		return person;

	}

	public static void delete(Person person) {
		Session session = sessionFactory.openSession();

		session.beginTransaction();

		session.delete(person);

		session.getTransaction().commit();

	}
	
	public static List<Person> findAll(){
		Session session = sessionFactory.openSession();
		@SuppressWarnings("unchecked")
		List<Person> persons = session.createQuery("from Person").list();
		return persons;
	}
}


Step 11. Create PassportDAO class: PassportDAO class to insert/update/get/delete records into database.

PassportDAO.java

package com.hibernate.hbm.dao;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.hibernate.hbm.pojo.PassportDetail;
import com.hibernate.hbm.util.HibernateUtility;

public class PassportDAO {
	private static SessionFactory sessionFactory;
	static {
		sessionFactory = HibernateUtility.getSessionFactory();
	}

	public static PassportDetail findById(int id) {
		Session session = sessionFactory.openSession();
		PassportDetail passportDetail = (PassportDetail) session.get(PassportDetail.class, id);
		return passportDetail;
	}
	
	public static PassportDetail save(PassportDetail passportDetail) {
		Session session = sessionFactory.openSession();

		session.beginTransaction();

		session.save(passportDetail);

		session.getTransaction().commit();

		return passportDetail;
	}

	public static PassportDetail update(PassportDetail passportDetail) {
		Session session = sessionFactory.openSession();

		session.beginTransaction();

		session.merge(passportDetail);

		session.getTransaction().commit();

		return passportDetail;

	}

	public static void delete(PassportDetail passportDetail) {
		Session session = sessionFactory.openSession();

		session.beginTransaction();

		session.delete(passportDetail);

		session.getTransaction().commit();

	}
	
	public static List<PassportDetail> findAll(){
		Session session = sessionFactory.openSession();
		@SuppressWarnings("unchecked")
		List<PassportDetail> passportDetails = session.createQuery("from PassportDetail").list();
		return passportDetails;
	}
}


Step 12. Create a PersonPassportService class: PersonPassportService class to call the methods of DAO class, specially PassportDAO methods.

PersonPassportService.java

package com.hibernate.hbm.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import com.hibernate.hbm.dao.PassportDAO;
import com.hibernate.hbm.pojo.PassportDetail;
import com.hibernate.hbm.pojo.Person;

public class PersonPassportService {

	public static void main(String[] args) {
 
		Person person = new Person();
		person.setFirstName("Tony");
		person.setLastName("Leo");
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		PassportDetail passportDetail = new PassportDetail();
		try {
			person.setDateOfBirth(sdf.parse("1990-10-10"));
			passportDetail.setDateOfExpiry(sdf.parse("2010-10-10"));
			passportDetail.setDateOfIssue(sdf.parse("2020-10-09"));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
 
		passportDetail.setPassportNo("L1025698");
 
		passportDetail.setPerson(person);
 
		// saving person record into the database.
		//It will generate an insert query for person table only.
		//System.out.println(PersonDAO.save(person));
		
		
		// saving passport detail into the database.
		// it will generate two insert query, one for person and one for passport detail
		System.out.println(PassportDAO.save(passportDetail));
		
	}
}


That's it, Now run PersonPassportService class you will get output at your console where two insert query will executed one for Person and one for PasspportDetail table, along with passport details because we are overriding the toString() method inside PassportDetail.java class.

OUT PUT:
Hibernate: insert into person (first_name, last_name, date_of_birth) values (?, ?, ?)
Hibernate: insert into passport_detail (passport_number, date_of_issue, date_of_expiry, person_id) values (?, ?, ?, ?)
PassportDetail [passportNo=L1025698, dateOfIssue=2020-10-09, dateOfExpiry=2010-10-10, person=Person [personId=2, firstName=Tony, lastName=Leo, dateOfBirth=1990-10-10]]

Download the complete example from here Source Code

For required jar files you may download it from hibernate.org or from my previous post, here

Reference
Sponsored Links

0 comments:

Post a Comment