Hibernate One to One XML Mapping Example

Every application needs relation between two or more tables.Here I am going to take an example to show One-to-One relation between two tables through XML mapping.Hibernate provides <one-to-one> and <many-to-one> relations for the same.

Project Setup

Add hibernate following jars to the project using Right Click->Build Path->Add Exertnal Archieves.

  • antlr-2.7.6
  • cglib-2.2
  • commons-collections-3.1
  • dom4j
  • ehcache-1.2.3
  • hibernate3
  • javassist-3.9.0.GA
  • jta-1.1
  • log4j-1.2.14
  • slf4j-api-1.5.8
  • slf4j-log4j12-1.5.8
  • commons-logging-1.1.3.jar
  • commons-lang3-3.1.jar

hibernate one to one mapping example

Database Setup

CREATE TABLE IF NOT EXISTS `category` (
  `id` int(11) NOT NULL,
  `title` varchar(255) DEFAULT NULL,
  `description` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `product` (
  `id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `description` varchar(255) DEFAULT NULL,
  `price` float DEFAULT NULL,
  `category` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `category` (`category`),
  KEY `FK50C664CFE8116EBB` (`category`),
  CONSTRAINT `FK50C664CFE8116EBB` FOREIGN KEY (`category`) REFERENCES `category` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Entity Classes

There are two beans classes named Product and Category.Product class has reference of Category class for one-to-one relation.

Category.java

package com.startwithjava.beans;

public class Category {
	private int id;
	private String title;
	private String description;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
}

Product.java

package com.startwithjava.beans;
public class Product {
	private int id;
	private String name;
	private String description;
	private Category category;
	private double price;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Category getCategory() {
		return category;
	}
	public void setCategory(Category category) {
		this.category = category;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
}

Mapping Files for Persistent class

There are two XML mapping files for both two entity classes named product.hbm.xml and category.hbm.xml.These mapping files contain information about column,data types,entity class name and relation.

category.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 
      
    <hibernate-mapping>  
    <class name="com.startwithjava.beans.Category">  
    <id name="id">  
    	<generator class="increment"></generator>  
    </id>  
    <property name="title"></property> 
    <property name="description"></property> 
    </class>  
                
</hibernate-mapping>  

product.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 
     <hibernate-mapping>  
      <class name="com.startwithjava.beans.Product">  
        <id name="id">  
         <generator class="increment"></generator>  
        </id>            
        <property name="name"></property>  
        <property name="description"></property>
        <property name="price" type="double"></property>
        <one-to-one name="category" constrained="true" cascade="all"></one-to-one>            
      </class>           
     </hibernate-mapping>  

Hibernate Configuration

Hibernate configuration file contains information about driver class,database user,database password etc.

hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
     <session-factory>  
         <property name="hbm2ddl.auto">update</property>  
         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
         <property name="connection.url">jdbc:mysql://localhost:3306/yourdbname</property>  
         <property name="connection.username">root</property>  
         <property name="connection.password"></property>  
         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>  
     <mapping resource="product.hbm.xml"/>  
     <mapping resource="category.hbm.xml"/> 
     </session-factory>  
</hibernate-configuration>  

OneToOneTest.java

package com.startwithjava.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.startwithjava.beans.Category;
import com.startwithjava.beans.Product;

public class OneToOneTest {
	public static void main(String[] args) {  
	    Configuration cfg=new Configuration();  
	    cfg.configure("hibernate.cfg.xml");  
	    SessionFactory sf=cfg.buildSessionFactory();  
	    Session session=sf.openSession();  
	    Transaction tx=session.beginTransaction();  
	    Category category = new Category();
	    category.setTitle("Caegory 1");
	    category.setDescription("Caegory 1 11");
	    Product product = new Product();
	    product.setName("A");
	    product.setDescription("Description");
	    product.setCategory(category);
	    product.setPrice(500);
	    session.save(product);
	    tx.commit();
	    Product p2 = (Product) session.get(Product.class,new Integer(1));
	    System.out.println("Product Details:\n"+"Product Title:"+p2.getName()+"\t Price:"+p2.getPrice()+"\tCategory title"+p2.getCategory().getTitle());
	    session.close();
	}
}

One Reply to “Hibernate One to One XML Mapping Example”

Leave a Reply