• RubyonRails
  • Struts
  • SQL Tutorial
  • JavaScript
  • PHP
  • Servlet
  • jQuery
  • Spring
  • Core Java

  • <

    Hibernate One to One Mapping


    Most of the times, database tables are associated with each other. There are many forms of association ?? one-to-one, one-to-many and many-to-many are at the broad level, that can be further divided into unidirectional and bidirectional mappings. This tutorial guides you through implementing Hibernate One to One Mapping using XML configuration as well as using JPA annotations configuration.

    Example

    
    -- Create Transaction Table
    CREATE TABLE `Transaction` (
      `txn_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
      `txn_date` date NOT NULL,
      `txn_total` decimal(10,0) NOT NULL,
      PRIMARY KEY (`txn_id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;
    
    -- Create Customer table
    CREATE TABLE `Customer` (
      `txn_id` int(11) unsigned NOT NULL,
      `cust_name` varchar(20) NOT NULL DEFAULT '',
      `cust_email` varchar(20) DEFAULT NULL,
      `cust_address` varchar(50) NOT NULL DEFAULT '',
      PRIMARY KEY (`txn_id`),
      CONSTRAINT `customer_ibfk_1` FOREIGN KEY (`txn_id`) REFERENCES `Transaction` (`txn_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    

    Hibernate Maven Dependencies


    pom.xml

    
    <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.journaldev.hibernate</groupId>
      <artifactId>HibernateOneToOneMapping</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <dependencies>
      	<dependency>
      		<groupId>org.hibernate</groupId>
      		<artifactId>hibernate-core</artifactId>
      		<version>4.3.5.Final</version>
      	</dependency>
      	<dependency>
      		<groupId>mysql</groupId>
      		<artifactId>mysql-connector-java</artifactId>
      		<version>5.0.5</version>
      	</dependency>
      </dependencies>
    </project>
    


    Hibernate One to One Mapping Model Classes



    
    
    package com.tutorial.hibernate.model;
    
    import java.util.Date;
    
    public class Txn {
    
    	private long id;
    	private Date date;
    	private double total;
    	private Customer customer;
    	
    	@Override
    	public String toString(){
    		return id+", "+total+", "+customer.getName()+", "+customer.getEmail()+", "+customer.getAddress();
    	}
    	public long getId() {
    		return id;
    	}
    	public void setId(long id) {
    		this.id = id;
    	}
    	public Date getDate() {
    		return date;
    	}
    	public void setDate(Date date) {
    		this.date = date;
    	}
    	public double getTotal() {
    		return total;
    	}
    	public void setTotal(double total) {
    		this.total = total;
    	}
    	public Customer getCustomer() {
    		return customer;
    	}
    	public void setCustomer(Customer customer) {
    		this.customer = customer;
    	}
    	
    }
    

    Customer Class

    
    package com.tutorial.hibernate.model;
    
    public class Customer {
    
    	private long id;
    	private String name;
    	private String email;
    	private String address;
    	
    	private Txn txn;
    	
    	public long getId() {
    		return id;
    	}
    	public void setId(long id) {
    		this.id = id;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public String getEmail() {
    		return email;
    	}
    	public void setEmail(String email) {
    		this.email = email;
    	}
    	public String getAddress() {
    		return address;
    	}
    	public void setAddress(String address) {
    		this.address = address;
    	}
    	public Txn getTxn() {
    		return txn;
    	}
    	public void setTxn(Txn txn) {
    		this.txn = txn;
    	}
    	
    }
    
    


    one to one mapping configuration


    txn.hbm.xml

    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    	"http://hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
    	<class name="com.journaldev.hibernate.model.Txn" table="TRANSACTION" >
    		<id name="id" type="long">
    			<column name="txn_id" />
    			<generator class="identity" />
    		</id>
    		<property name="date" type="date">
    			<column name="txn_date" />
    		</property>
    		<property name="total" type="double">
    			<column name="txn_total" />
    		</property>
    		<one-to-one name="customer" class="com.tutorial.hibernate.model.Customer"
    			cascade="save-update" />
    	</class>
    	
    </hibernate-mapping>
    


    customer.hbm.xml

    
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
    "http://hibernate.org/dtd/hibernate-mapping-3.0.dtd" >
    <hibernate-mapping>
    
    	<class name="com.journaldev.hibernate.model.Customer" table="CUSTOMER">
    		<id name="id" type="long">
    			<column name="txn_id" />
    			<generator class="foreign">
    				<param name="property">txn</param>
    			</generator>
    		</id>
    		<one-to-one name="txn" class="com.journaldev.hibernate.model.Txn"
    			constrained="true"></one-to-one>
    
    		<property name="name" type="string">
    			<column name="cust_name"></column>
    		</property>
    		<property name="email" type="string">
    			<column name="cust_email"></column>
    		</property>
    		<property name="address" type="string">
    			<column name="cust_address"></column>
    		</property>
    	</class>
    
    </hibernate-mapping>
    
    
    
    

    Hibernate Configuration File



    hibernate.cfg.xml

    
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC
    		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    		"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
        <session-factory>
            <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="hibernate.connection.password"&root123</property>
            <property name="hibernate.connection.url">jdbc:mysql://localhost/TestDB</property>
            <property name="hibernate.connection.username"&root</property>
            <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
            
            <property name="hibernate.current_session_context_class">thread</property>
            <property name="hibernate.show_sql">true</property>
            
            <mapping resource="txn.hbm.xml"/>
            <mapping resource="customer.hbm.xml"/>
        </session-factory>
    </hibernate-configuration>
    
    


    Hibernate SessionFactory Utility



    
    package com.journaldev.hibernate.util;
    
    import org.hibernate.SessionFactory;
    import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.service.ServiceRegistry;
    
    public class HibernateUtil {
    
    	private static SessionFactory sessionFactory;
    	
    	private static SessionFactory buildSessionFactory() {
            try {
                // Create the SessionFactory from hibernate.cfg.xml
            	Configuration configuration = new Configuration();
            	configuration.configure("hibernate.cfg.xml");
            	System.out.println("Hibernate Configuration loaded");
            	
            	ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
            	System.out.println("Hibernate serviceRegistry created");
            	
            	SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
            	
                return sessionFactory;
            }
            catch (Throwable ex) {
                System.err.println("Initial SessionFactory creation failed." + ex);
                ex.printStackTrace();
                throw new ExceptionInInitializerError(ex);
            }
        }
    	
    	public static SessionFactory getSessionFactory() {
    		if(sessionFactory == null) sessionFactory = buildSessionFactory();
            return sessionFactory;
        }
    }
    
    
    
    
    

    One to One Mapping Test



    
    package com.tutorial.hibernate.main;
    
    import java.util.Date;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    
    import com.journaldev.hibernate.model.Customer;
    import com.journaldev.hibernate.model.Txn;
    import com.journaldev.hibernate.util.HibernateUtil;
    
    public class HibernateOneToOneMain {
    
    	public static void main(String[] args) {
    		
    		Txn txn = buildDemoTransaction();
    		
    		SessionFactory sessionFactory = null;
    		Session session = null;
    		Transaction tx = null;
    		try{
    		//Get Session
    		sessionFactory = HibernateUtil.getSessionFactory();
    		session = sessionFactory.getCurrentSession();
    		System.out.println("Session created");
    		//start transaction
    		tx = session.beginTransaction();
    		//Save the Model object
    		session.save(txn);
    		//Commit transaction
    		tx.commit();
    		System.out.println("Transaction ID="+txn.getId());
    		
    		//Get Saved Trasaction Data
    		printTransactionData(txn.getId(), sessionFactory);
    		
    		}catch(Exception e){
    			System.out.println("Exception occured. "+e.getMessage());
    			e.printStackTrace();
    		}finally{
    			if(!sessionFactory.isClosed()){
    				System.out.println("Closing SessionFactory");
    				sessionFactory.close();
    			}
    		}
    	}
    
    	private static void printTransactionData(long id, SessionFactory sessionFactory) {
    		Session session = null;
    		Transaction tx = null;
    		try{
    			//Get Session
    			sessionFactory = HibernateUtil.getSessionFactory();
    			session = sessionFactory.getCurrentSession();
    			//start transaction
    			tx = session.beginTransaction();
    			//Save the Model object
    			Txn txn = (Txn) session.get(Txn.class, id);
    			//Commit transaction
    			tx.commit();
    			System.out.println("Transaction Details=\n"+txn);
    			
    			}catch(Exception e){
    				System.out.println("Exception occured. "+e.getMessage());
    				e.printStackTrace();
    			}
    	}
    
    	private static Txn buildDemoTransaction() {
    		Txn txn = new Txn();
    		txn.setDate(new Date());
    		txn.setTotal(100);
    		
    		Customer cust = new Customer();
    		cust.setAddress("odisha");
    		cust.setEmail("ss@gmail.com");
    		cust.setName("sunil sahu");
    		
    		txn.setCustomer(cust);
    		
    		cust.setTxn(txn);
    		return txn;
    	}
    
    }
    

    OUTPUT



    Hibernate Configuration loaded
    Hibernate serviceRegistry created
    Session created
    Hibernate: insert into TRANSACTION (txn_date, txn_total) values (?, ?)
    Hibernate: insert into CUSTOMER (cust_name, cust_email, cust_address, txn_id) values (?, ?, ?, ?)
    Transaction ID=19
    Hibernate: select txn0_.txn_id as txn_id1_1_0_, txn0_.txn_date as txn_date2_1_0_, txn0_.txn_total as txn_tota3_1_0_,
    customer1_.txn_id as txn_id1_0_1_, customer1_.cust_name as cust_nam2_0_1_, customer1_.cust_email as cust_ema3_0_1_,
    customer1_.cust_address as cust_add4_0_1_ from TRANSACTION txn0_ left outer join CUSTOMER customer1_ on
    txn0_.txn_id=customer1_.txn_id where txn0_.txn_id=?
    Transaction Details=
    19, 100.0, sunil sahu, ss@gmail.com, odisha
    Closing SessionFactory











    © copyright 2017-2021 Completedone pvt ltd.