Hibernate One to One Relationship Xml Mapping Example

 Posted On  | Yashwant Chavan 

First Of all we need to see What is One to One Relationship, for every record in the one table there is one and only one record in the related table. In Hibernate we can achieve One to One relationship using Xml Mapping And using annotation also, Below hibernate tutorial explain you how two tables are link with each other with the help of one to one mapping using Xml base mapping approach.

When Sql Joins comes in picture, there is always relationship between tables, Number of tables are associated with each other with the help of keys. Today we are going to discuss on one-to-one relationship in Hibernate, How hibernate manage the relationship between tables using xml mapping.

Tools and Technologies

To execute sample hibernate program we use below technologies

  1. Maven 3.0.4
  2. JDK 1.6
  3. Hibernate 3.2.6.ga
  4. MySql 5.1

Hibernate Maven Project

Create sample Maven base Project using Eclipse Wizard

Hibernate One to One Mapping Example

Hibernate Dependency (pom.xml)

Once your Maven base project has been created using Eclipse, Define the below hibernate and other dependencies in pom.xml 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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.technicalkeeda.spring</groupId>
	<artifactId>com.technicalkeeda.spring</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringExamples</name>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<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.6.ga</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-annotations</artifactId>
			<version>3.3.1.GA</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>dom4j</groupId>
			<artifactId>dom4j</artifactId>
			<version>1.6.1</version>
		</dependency>

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

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

		<dependency>
			<groupId>javax.transaction</groupId>
			<artifactId>jta</artifactId>
			<version>1.1</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>SpringExamples</finalName>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Mapping Files and Model Classes

Create Customer and CustomerDetails model class with annotation @Entity

package com.technicalkeeda.entities;

import javax.persistence.Entity;

@Entity
public class Customer implements java.io.Serializable {
	private long customerId;
	private String firstName;
	private String lastName;

	private CustomerDetails customerDetails;

	public Customer() {
	};

	public Customer(long customerId, String firstName, String lastName) {
		super();
		this.customerId = customerId;
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public long getCustomerId() {
		return customerId;
	}

	public void setCustomerId(long customerId) {
		this.customerId = customerId;
	}

	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 CustomerDetails getCustomerDetails() {
		return customerDetails;
	}

	public void setCustomerDetails(CustomerDetails customerDetails) {
		this.customerDetails = customerDetails;
	}

}

CustomerDetails.java

package com.technicalkeeda.entities;

import java.util.Date;

import javax.persistence.Entity;

@Entity
public class CustomerDetails implements java.io.Serializable {

	private long customerId;
	private String height;
	private String weight;
	private Date birthDate;

	private Customer customer;

	public CustomerDetails() {
	}

	public CustomerDetails(long customerId, String height, String weight,
			Date birthDate) {
		super();
		this.customerId = customerId;
		this.height = height;
		this.weight = weight;
		this.birthDate = birthDate;
	}

	public long getCustomerId() {
		return customerId;
	}

	public void setCustomerId(long customerId) {
		this.customerId = customerId;
	}

	public String getHeight() {
		return height;
	}

	public void setHeight(String height) {
		this.height = height;
	}

	public String getWeight() {
		return weight;
	}

	public void setWeight(String weight) {
		this.weight = weight;
	}

	public Date getBirthDate() {
		return birthDate;
	}

	public void setBirthDate(Date birthDate) {
		this.birthDate = birthDate;
	}

	public Customer getCustomer() {
		return customer;
	}

	public void setCustomer(Customer customer) {
		this.customer = customer;
	}

}

Customer Mapping Files

Mapping file is used to define Customer table attributes

<?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>
	<class name="com.technicalkeeda.entities.Customer" table="trn_customer"
		catalog="technicalkeeda">
		<id name="customerId" type="java.lang.Long">
			<column name="customer_id" />
			<generator class="identity" />
		</id>
		<property name="firstName" type="string">
			<column name="first_name" length="20" not-null="true" />
		</property>
		<property name="lastName" type="string">
			<column name="last_name" length="20" not-null="true" />
		</property>
		<one-to-one name="customerDetails" class="com.technicalkeeda.entities.CustomerDetails"
			cascade="save-update"></one-to-one>
	</class>
</hibernate-mapping>

CustomerDetails Mapping Files

Mapping file is used to define CustomerDetails tables attributes

<?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>
	<class name="com.technicalkeeda.entities.CustomerDetails" table="trn_customer_details"
		catalog="technicalkeeda">
		<id name="customerId" type="java.lang.Long">
			<column name="customer_id" />
			<generator class="foreign">
				<param name="property">customer</param>
			</generator>
		</id>
		<one-to-one name="customer" class="com.technicalkeeda.entities.Customer" constrained="true"></one-to-one>
		<property name="height" type="string">
			<column name="height" length="10" not-null="true" />
		</property>
		<property name="weight" type="string">
			<column name="weight" length="10" not-null="true" />
		</property>
		<property name="birthDate" type="date">
			<column name="birth_date" length="10" not-null="true" />
		</property>
	</class>
</hibernate-mapping>

Hibernate Configuration file (Create Hibernate Configuration file)

Create Hibernate Configuration file and put it under src/main/resources/hibernate.cfg.xml directory

<?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="connection.url">jdbc:mysql://localhost:3306/technicalkeeda</property>
		<property name="connection.username">root</property>
		<property name="connection.password"></property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="show_sql">true</property>
		<property name="format_sql">true</property>
		<property name="hbm2ddl.auto">create</property>
		<property name="connection.pool_size">1</property>
		<property name="current_session_context_class">thread</property>
		<mapping resource="com/technicalkeeda/entities/Customer.hbm.xml"></mapping>
		<mapping resource="com/technicalkeeda/entities/CustomerDetails.hbm.xml"></mapping>		
	</session-factory>
</hibernate-configuration>

Test You Program (App.java)

Build your maven project and execute the App.java class, It is going to create two tables in the database as "trn_customer" and "trn_customer_details" Which are linked with each other by one to one relationship

package com.technicalkeeda.test;

import java.util.Date;

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

import com.technicalkeeda.entities.Customer;
import com.technicalkeeda.entities.CustomerDetails;

public class App {
	public static void main(String[] args) {
		SessionFactory sessionFactory = new AnnotationConfiguration()
				.configure().buildSessionFactory();
		Session session = sessionFactory.getCurrentSession();

		Transaction tx = session.beginTransaction();

		Customer customer = new Customer();
		customer.setFirstName("Yashwant");
		customer.setLastName("Chavan");

		CustomerDetails customerDetails = new CustomerDetails();
		customerDetails.setHeight("5Ft-10Inch");
		customerDetails.setWeight("70Kg");
		Date birthDate = new Date();
		customerDetails.setBirthDate(birthDate);
		customerDetails.setCustomer(customer);

		customer.setCustomerDetails(customerDetails);

		session.save(customer);
		tx.commit();
	}
}

Output Tables (Customer and CustomerDetails)

trn_customer and trn_customer_details tables are created as per Customer and CustomerDetails hibernate mapping file.

Hibernate One to One Table Relationship

Output

When you execute the App.java , output will look like this.

Hibernate: 
    insert 
    into
        technicalkeeda.trn_customer
        (first_name, last_name) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        technicalkeeda.trn_customer_details
        (height, weight, birth_date, customer_id) 
    values
        (?, ?, ?, ?)

Finish

Hope this Hibernate One to One relationship Tutorial is useful to you, Please fill free to provide your comments if there is any problem. Thanks

Tags Hibernate  Hibernate Relationship  Hibernate One To One Mapping  Hibernate Tutorial 


Similar Articles

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: SIMILAR_ARTICLE

Filename: views/articledetails.php

Line Number: 83

HTML Comment Box is loading comments...

Hi I am Yashwant Chavan founder of www.technicalkeeda.com, Purpose of this website to share the programming knowledge in the form post , blogs and articles.

Latest Updates

Stay updated with latest post, articles and technical discussions.

Most Popular Articles



© technicalkeeda.com 2014