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 annotation. Before that lets have a look what exactly one-to-one association in RDBMS ? One-to-One association means, Each row of table is mapped with exactly one and only one row with another table.
For example, we have a passport_detail and person table each row of person table is mapped with exactly one and only one row of passport_detail table. One person has only one passport.

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
  • annotated pojo
  • 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` (
  `passport_id` int(11) NOT NULL AUTO_INCREMENT,
  `date_of_expiry` date DEFAULT NULL,
  `date_of_issue` date DEFAULT NULL,
  `passport_number` varchar(255) DEFAULT NULL,
  `person_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`passport_id`),
  KEY `FK_5rxo4attorxuavdigd8k9ysf8` (`person_id`),
  CONSTRAINT `FK_5rxo4attorxuavdigd8k9ysf8` FOREIGN KEY (`person_id`) REFERENCES `person` (`person_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

/*Table structure for table `person` */

DROP TABLE IF EXISTS `person`;

CREATE TABLE `person` (
  `person_id` int(11) NOT NULL AUTO_INCREMENT,
  `date_of_birth` date DEFAULT NULL,
  `first_name` varchar(255) DEFAULT NULL,
  `last_name` varchar(255) 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 here. 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>
         
        <!-- SQL 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 class="com.hibernate.annotations.pojo.Person"/>
        <mapping class="com.hibernate.annotations.pojo.PassportDetail"/>
                   
    </session-factory>
</hibernate-configuration>

Step 5. Create PassportDetail annotated class:

PassportDetail.java

package com.hibernate.annotations.pojo;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name = "passport_detail")
public class PassportDetail {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "passport_id", unique = true, nullable = false)
	private Integer passportId;
	
	@Column(name = "passport_number")
	private String passportNo;

	@Temporal(TemporalType.DATE)
	@Column(name = "date_of_issue")
	private Date dateOfIssue;

	@Temporal(TemporalType.DATE)
	@Column(name = "date_of_expiry")
	private Date dateOfExpiry;

	@OneToOne
    @JoinColumn(name = "person_id")
	private Person person;

	public Integer getPassportId() {
		return passportId;
	}

	public void setPassportId(Integer passportId) {
		this.passportId = passportId;
	}

	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 [passportId=" + passportId + ", passportNo="
				+ passportNo + ", dateOfIssue=" + dateOfIssue
				+ ", dateOfExpiry=" + dateOfExpiry + ", person=" + person + "]";
	}
	
}

Step 6. Create Person annotated class:

Person.java

package com.hibernate.annotations.pojo;

import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;


@Entity
@Table(name="person")
public class Person {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "person_id", unique = true, nullable = false)
	private Integer personId;
	
	@Column(name="first_name")
	private String firstName;
	
	@Column(name="last_name")
	private String lastName;
	
	@Temporal(TemporalType.DATE)
	@Column(name="date_of_birth")
	private Date dateOfBirth;
	
    @OneToOne(mappedBy = "person",cascade=CascadeType.ALL)
	private PassportDetail passportDetail;

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

	public PassportDetail getPassportDetail() {
		return passportDetail;
	}

	public void setPassportDetail(PassportDetail passportDetail) {
		this.passportDetail = passportDetail;
	}

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

}


Step 7. 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 8. 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();
		List<Person> persons = session.createQuery("from Person").list();
		return persons;
	}
}

Step 9. Create PersonPassportService class: Service class to call the methods of PersonDAO class.

PersonPassportService.java

package com.hibernate.annotations.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import com.hibernate.annotations.dao.PersonDAO;
import com.hibernate.annotations.pojo.PassportDetail;
import com.hibernate.annotations.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.setDateOfIssue(sdf.parse("2010-10-10"));
			passportDetail.setDateOfExpiry(sdf.parse("2020-10-09"));
		} catch (ParseException e) {
			e.printStackTrace();
		}
 
		passportDetail.setPassportNo("Q12345678");
 
		person.setPassportDetail(passportDetail);
		passportDetail.setPerson(person);
 
		// saving person it will generate two insert query.
		System.out.println(PersonDAO.save(person));
 
		
	}
}


That's it, Now run the 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 Person.java class.

OUT PUT:
Hibernate: insert into person (date_of_birth, first_name, last_name) values (?, ?, ?)
Hibernate: insert into passport_detail (date_of_expiry, date_of_issue, passport_number, person_id) values (?, ?, ?, ?)
Person [personId=1, firstName=Tony, lastName=Leo, dateOfBirth=1990-10-10]


Download the complete example from here Source Code


You can download the same application using hbm.xml from here One-to-One association using hbm.xml
For required jar files you may download it from hibernate.org or from my previous post, here

Sponsored Links

0 comments:

Post a Comment