Advertisement :
   Log In    OR    Register  
  Topics :  
RMI Example

Home >>> Hibernate Tutorial >>> Hibernate one to one >>> Mapping Example
Struts Tutorials:
Struts2 Tag CheckBoxList
, Checkbox, Iterator, IF
Struts2 Tag Library Example Struts2 Tiles Example Struts2 Tiles I18N Example Struts2 Questions Struts Tiles I18N Example Struts Eclipse MVC Struts2 Tags Struts2 Example and Tutorial Struts MVC Struts2 Validation
Hibernate Tutorials: Hibernate Case Study Class Hierarchy Persist Example Using Hibernate Interceptor Hibernate Questions with Answer Hibernate Many-to-Many Mapping Example Hibernate one-to-many Mapping Example Hibernate and ORM tools Spring Hibernate Example Hibernate SessionFactory Example Hibernate Mapping Class Hierarchy Hibernate Questions Hibernate SessionFactory Questions Spring Hibernate Example: Spring Hibernate Case Study

Written By : Amit
Title :
ways create Hibernate SessionFactory
Description : Example
More...


Written By : Amit
Title :
Spring Hibernate Integration example
Description : Example
More...


Written By : Amit
Title :
ORM Hibernate Best FIT
Description : Discussion
More...


Written By : Amit
Title :
One to Many mapping example
Description : Code
More...


Written By : Amit
Title :
Many to Many Mapping Example
Description : code
More...


Written By : Amit
Title :
Interview questions answer
Description : discussion
More...


Written By : Amit
Title :
Interceptor use log SQL statements
Description : example code
More...


Written By : Amit
Title :
Class Hierarchy Persist example
Description : code
More...

Tags/Keywords : Hibernate one to one, Hibernate, one to one, Mapping Example, Code, Tutorial, Article
Author : ISHTEK
Date (Year/Month/Date): 2009-07-01 Tag: Hibernate one to one mapping example

Please be informed that NONE of the design/code from this
page is claiming to be some sort of best practices and we DO NOT expect
any of our visitor/reader of this page to assume this as some sort of
best practice for any context and should not be using this 
as it is without appropriate evaluation to their, so to say, 
specific programming context.

This page intends only to provide bit and piece of known ways  for
doing some sort of example and may not be fit for any other purpose.

Example on setting up a one to one mapping between two Entities using Hibernate as persistence ORM tool Example case study: Car and Registration number are basically related to each other as one two one, that means for a single car, there could be at most a single registration number, and vice versa. so basically there is a one to one mapping between car and registration number for this car. We have two POJO defined, one is Car and the other one is RegistrationDetails, as follows:
Advertisement :
Car.java
package example;

public class Car {
  private String carName;
  private String model;
  private String segment;
  private RegistrationDetails registrationDetails;
public String getCarName() {
	return carName;
}
public void setCarName(String carName) {
	this.carName = carName;
}
public String getModel() {
	return model;
}
public void setModel(String model) {
	this.model = model;
}
public RegistrationDetails getRegistrationDetails() {
	return registrationDetails;
}
public void setRegistrationDetails(RegistrationDetails registrationDetails) {
	this.registrationDetails = registrationDetails;
}
public String getSegment() {
	return segment;
}
public void setSegment(String segment) {
	this.segment = segment;
}
}
RegistrationDetails.java
package example;

import java.util.Date;

public class RegistrationDetails {
  private String registrationNumber;
  private String placeOfIssue;
  private Date issuedDate;
  private Car car;
public Car getCar() {
	return car;
}
public void setCar(Car car) {
	this.car = car;
}
public Date getIssuedDate() {
	return issuedDate;
}
public void setIssuedDate(Date issuedDate) {
	this.issuedDate = issuedDate;
}
public String getPlaceOfIssue() {
	return placeOfIssue;
}
public void setPlaceOfIssue(String placeOfIssue) {
	this.placeOfIssue = placeOfIssue;
}
public String getRegistrationNumber() {
	return registrationNumber;
}
public void setRegistrationNumber(String registrationNumber) {
	this.registrationNumber = registrationNumber;
}
}
In order to come up with mapping HBM XML file, we need to understand the basic tables being used to persist these entities in database (in this example, I have used HSQLDB 1.7.0) We can't have Car and Registration related tables share primary key and foreign key relationship, as these will lead to one to many type of mapping. Instead we shall have to use Unique constraint on the field/column that is used to tie these two Entities together for achieving a single row in the dependent table and a primary key constraint on the main table. By this we should be able to have a constrained one to one mapping. So I have decided to use primary key for the car_name column from car related table, and Unique key constraint for the car_name in the registration details related table. DDL db script (HSQLDB 1.7.0 as database) for this example as follows:
create table car
(car_name varchar(20), car_model varchar(50), 
 car_segment varchar(50), primary key (car_name))

create table registration_details
(registration_number varchar(20), issue_place varchar(50),
 issue_date date, car_name varchar(20) not null, 
 primary key(registration_number), unique(car_name))
car-registration.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">
<hibernate-mapping package="example">
  <class name="Car" table="Car">
  	<id name="carName" access="property" column="car_name"/>
 	<property name="model" column="car_model"/>
  	<property name="segment" column="car_segment"/>
  </class>
  <class name="RegistrationDetails" table="registration_details">
    <id name="registrationNumber" access="property" 
                                             column="registration_number"/>
 	<property name="placeOfIssue" column="issue_place"/>
  	<property name="issuedDate" column="issue_date" type="java.util.Date"/>
  	<many-to-one name="car" column="car_name" unique="true" not-null="true" 
  	                                                     cascade="persist"/>
  </class>
</hibernate-mapping>
You might have noticed that instead of using one-to-one tag I have used many-to-one tag, but with unique as true, not-null as true and cascade as persist, so as to be able to persist a single record for registration details and as well as the associated car details in car table as well. Please see this diagram below, so as to be able to understand how the mapping configuration HBM file is referring to class and database model. This example uses hibernate.cfg.xml file for the configuration related to creation of Hibernate SessionFactory, as shown below: 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>

        <!-- Database connection settings -->
    <property name="connection.driver_class">
		  org.hsqldb.jdbcDriver
    </property>
    <property name="connection.url">
		  jdbc:hsqldb:hsql://localhost/
    </property>
    <property name="connection.username">sa</property>
    <property name="connection.password"></property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="dialect">
		  org.hibernate.dialect.HSQLDialect
	</property>

    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">
		  thread
	</property>

		<!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <mapping resource="example/car-registration.hbm.xml"/>

    </session-factory>

</hibernate-configuration>
Test client for this one to one mapping example is very straight forward. I am creating a SessionFactory and then getting a Session from it for persisting both Car and RegistrationDetails POJO as Hibernate Entities. Client.java
// This source is provided on "AS IS" basis.
package example;

import java.util.Calendar;

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

import demo.interceptor.CaptureSQL;
import demo.profile.Address;
import demo.profile.Contact;
import demo.profile.Person;

import org.apache.log4j.Logger;

public class Client {

    private static final SessionFactory sessionFactory;
    static {
      try {
         // Create the SessionFactory from hibernate.cfg.xml
         sessionFactory = new Configuration().configure().buildSessionFactory();
        } 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 createRecord()
    {
		System.out.println(getSessionFactory());
		Session session = getSessionFactory().openSession(new CaptureSQL());
		Transaction trx = session.beginTransaction();
		trx.begin();
		Car car = new Car();
		car.setCarName("My Car");
		car.setModel("My Model");
		car.setSegment("My Segment");

		RegistrationDetails regDetails = new RegistrationDetails();
		//some hypothetical values are used in this example.
		regDetails.setRegistrationNumber("A0002223");
		regDetails.setPlaceOfIssue("Ahmedabad");
		Calendar c = Calendar.getInstance();
		c.set(2007, 01, 04);
		regDetails.setIssuedDate(c.getTime());
        regDetails.setCar(car);

        session.persist(regDetails);
		
		trx.commit();
		session.close();
    }
 	/**
	 * @param args
	 */
	public static void main(String[] args) {

		createRecord();
	}

}
There is another way of mapping one to one and this is by using one-to-one tag only. I shall discuss this on my next article, please keep reading and commenting on these articles for improvement. Thanks.
Advertisement :
Author of this article/writeup has expressed his/her willingness
to help or guide users with any technical difficulties he/she faces while working with the example code environment setting up, running and resolving any such exception raised during compile or at runtime. You may ask for any technical doubt or seek technical help related to this article by using following form to reach for technical help from the Author for FREE. This article's Author shall be reading your request and responding within reasonable time (no resolution timeframe defined as such).


	

Commented By ->
vishal
Hi,

I have read this article and it is really good one.

I am new for hibernate. Please tell me how to use one to one mapping using <one-to-one> tag.

Thanks
Vishal

Commented By ->
ISHTEK
In order to use <one-to-one> tag for achiving one to one
mapping using Hibernate, I have to modify this example, as 
follows:

To my understanding, in order to become an Entity, a class
should have the id field mapped to the primary key in 
corresponding table in database.

So we may have to have two class fles with the same name
for the id tag and both should refer to primary key in both
the corresponding tables.

For this example, Car class should have carName as the id
field, and refers to the car_name (defined as primary key
in car table), and RegistrationDetails class also should have
carName as the id field and refers to the car_name (which
is also defined as primary key in registration_detail table.)

So the DDL script should be changed to reflect this, as follows:
create table car
(car_name varchar(20), car_model varchar(50), 
 car_segment varchar(50), primary key (car_name))

create table registration_details
(registration_number varchar(20), issue_place varchar(50),
 issue_date date, car_name varchar(20), 
 primary key(car_name))
As the registration_details table has undergone change, so is the RegistrationDetails class file, as follows: RegistrationDetails.java
package example;

import java.util.Date;

public class RegistrationDetails {
  private String registrationNumber;
  private String placeOfIssue;
  private Date issuedDate;
  private String carName;

public String getCarName() {
	return carName;
}
public void setCarName(String carName) {
	this.carName = carName;
}

public Date getIssuedDate() {
	return issuedDate;
}
public void setIssuedDate(Date issuedDate) {
	this.issuedDate = issuedDate;
}
public String getPlaceOfIssue() {
	return placeOfIssue;
}
public void setPlaceOfIssue(String placeOfIssue) {
	this.placeOfIssue = placeOfIssue;
}
public String getRegistrationNumber() {
	return registrationNumber;
}
public void setRegistrationNumber(String registrationNumber) {
	this.registrationNumber = registrationNumber;
}
}
So as you can observe that the car related variable is being changed with the carName varibale, as we are looking for a one to one uni-directional mapping from Car -> RegistrationDetails only. Corresponding HBM file looks something like follows:
<?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 package="example">
  <class name="Car" table="Car">
   <id name="carName" access="property" column="car_name"/>
   <property name="model" column="car_model"/>
   <property name="segment" column="car_segment"/>
   <one-to-one name="registrationDetails" constrained="true" 
                                             cascade="all"/>
  </class>
  <class name="RegistrationDetails" table="registration_details">
    <id name="carName" access="property" column="car_name"/>
    <property name="placeOfIssue" column="issue_place"/>
    <property name="issuedDate" column="issue_date" 
                                             type="java.util.Date"/>
    <property name="registrationNumber" column="registration_number"/>
  </class>
</hibernate-mapping>
Client program undergoes changes in the way Hibernate Entities such as Car and RegistrationDetails are getting persisted as follows: ....... RegistrationDetails regDetails = new RegistrationDetails(); regDetails.setCarName("My Car"); regDetails.setRegistrationNumber("A0002223"); regDetails.setPlaceOfIssue("Ahmedabad"); Calendar c = Calendar.getInstance(); c.set(2007, 01, 04); regDetails.setIssuedDate(c.getTime()); Car car = new Car(); car.setCarName("My Car"); car.setModel("My Model"); car.setSegment("My Segment"); car.setRegistrationDetails(regDetails); session.persist(car); ....... As you can observe the portion marked as red above, are identical, thus obtaining one to one mapping between Car and RegistrationDetails. Hope this helps. Please write you comments on this. There could be possibility of achieving bi-directional one to one association as well. If you required I shall show that as well. Thanks.

Commented By ->
vipin
Though i am new to Hibernate but i did example based on one to one mapping many 
to many many mapping as well as many to one mapping i want to know CRUD example 
for any of the mapping which help me Hibernate better.
Thanks and regards
Vipin Kumar Gupta 

Commented By ->
Ishtek
For your information, there is question on one to one
mapping using Hibernate, can be found at
Hibernate
one to one questions
Are you interested in solving a very interesting Technology Stack while Playing this Game          

Please write your Comment on this Matter
(This will be visible if found suitable):
Name: *
Email (will not be displayed): *
Matter: *
17,26
Enter bigger number from above :*
Home >>> Hibernate Tutorial >>> Hibernate one to one >>> Mapping Example
Visitor/User referred related external URL:
(Visible upon review and approved by this site Administrator)
Referred By Name *:
Resource URL *: (e.g, URL should be starting with http://www.-----.---)
 
Resource Short Description *:
30,5
Enter bigger number from above : *

Please log in to add or reply to any matter<- requires login
Log in or Register
Copyright © 2008-2009, Interview-Questions-Tips-Forum, All Rights Reserved.
CONTACT    PRIVACY POLICY    DISCLAIMER
Terms of Use and Disclaimer :

This web site provides some of the information about various technologies, example 
code, tips, tutorials etc. Like any printed materials, content of these pages may 
become out of date over a period of time. Therefore all visitor/users of this web 
site are requested/advised to refer to the originating parties/sources for the 
latest changes and happenings for detailed information. This information is not 
intended to be a substitute for the original reference provided by the originating 
parties/sources.

By accessing and using this website in any ways, including, without
limitation, browsing the website pages, using any information, using any content and/or 
downloading any materials, you agree to and are bound by the terms of use 
described in this page and Usage Terms and Conditions. 
If you do not agree to all of 
the terms and conditions contained in the terms of use described in this
page and Usage Terms and Conditions, do not use this 
website in any manner. If you are using the website on behalf of your 
employer, you represent that you are authorized to accept these Terms of Use 
on your employer's behalf.

All Trademarks are property of their respective owner. Appropriate measure is being
taken for providing accurate and up-to-date information but like any printed materials,
these blog(s)/contents may eventually be outdated one day, so if you are using any 
of these information, please refer original content/documentation from respective sources. 
And under no circumstances shall the Author of these contents and/or this web site
be liable for any loss, damage, expense incurred or suffered which is claimed to have
occurred because of usage of the contents of this web site.
If you have any questions/queries/feedback/suggestions then please write to this web
site owner at contact.