One to One Mapping in Hibernate Example

In the previous tutorial we learned about the entity class has the field of the value type object and also has the collection of the value type objects.

In this tutorial of One to One Mapping in Hibernate Example we will learning what happens when an entity class has the field of the entity type object. Means that one entity is inside the one entity known as One-2-One Mapping. 

One to One Mapping in Hibernate Example

Hibernate Mapping One-to-One
In this example you will learn how to map one-to-one relationship using Hibernate. Consider the following relationship between UserDetails and Vehicle entity.

One to One Mapping in Hibernate

According to the relationship each user should have a unique vehicle.

One to One Mapping

For that we will use the following annotation.
@OneToOne:
Target:
Fields (including property get methods)Defines a single-valued association to another entity that has one-to-one multiplicity. It is not normally necessary to specify the associated target entity explicitly since it can usually be inferred from the type of the object being referenced. If the relationship is bidirectional, the non-owning side must use the mappedBy element of the @OneToOne annotation to specify the relationship field or property of the owning side. The @OneToOne annotation may be used within an embeddable class to specify a relationship from the embeddable class to an entity class.

Now we look the following Example related to the One to One mapping.

1. First Create Vehicle Class

Vehicle.java

package com.sdnext.hibernate.tutorial.dto;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name=”VEHICLE”)

public class Vehicle
{
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name=”VEHICLE_ID”)

    private int vehicleId;
   
    @Column(name=”VEHICLE_NAME”)
    private String vehicleName;
   
    public int getVehicleId() {
        return vehicleId;
    }
    public void setVehicleId(int vehicleId) {
        this.vehicleId = vehicleId;
    }
    public String getVehicleName() {
        return vehicleName;
    }
    public void setVehicleName(String vehicleName) {
        this.vehicleName = vehicleName;
    }
}

2. Create the User Class

UserDetails.java

package com.sdnext.hibernate.tutorial.dto;

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;

@Entity
@Table (name=”USER_DETAIL”)

public class UserDetails
{
    @Id
    @Column(name=”USER_ID”)
    @GeneratedValue(strategy=GenerationType.AUTO)

    private int    userId;
   
    @Column(name=”USER_NAME”)
    private String userName;
   
    @OneToOne
    @JoinColumn(name=”VEHICLE_ID”)

    private Vehicle vehicle;
   
    public Vehicle getVehicle() {
        return vehicle;
    }
    public void setVehicle(Vehicle vehicle) {
        this.vehicle = vehicle;
    }
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
}

3. Create the 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.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/hibernateDB</property>
         <property name=”connection.username”>root</property>
         <property name=”connection.password”>root</property>

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

        <!– SQL dialect –>
         <property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>

        <!– Enable Hibernate’s automatic session context management –>
          <property name=”current_session_context_class”>thread</property>
       
        <!– Disable the second-level cache –>
         <property name=”cache.provider_class”>org.hibernate.cache.NoCacheProvider</property>

        <!– Echo all executed SQL to stdout –>
         <property name=”show_sql”>true</property>
       
        <!– Drop and re-create the database schema on startup –>
         <property name=”hbm2ddl.auto”>create</property>
        
        
         <mapping class=”com.sdnext.hibernate.tutorial.dto.UserDetails”/>
         <mapping class=”com.sdnext.hibernate.tutorial.dto.Vehicle”/>
        
     </session-factory>
 </hibernate-configuration>

4. Create Test Demo class for run this code.

HibernateTestDemo.java

package com.sdnext.hibernate.tutorial;

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

import com.sdnext.hibernate.tutorial.dto.UserDetails;
import com.sdnext.hibernate.tutorial.dto.Vehicle;

public class HibernateTestDemo {
    /**
     * @param args
     */
    public static void main(String[] args)
    {
        UserDetails user = new UserDetails(); //create the user entity
        Vehicle vehicle = new Vehicle(); //create the vehicle entity
       
        vehicle.setVehicleName(“BMW Car”); //set vehicle name
       
        user.setUserName(“Dinesh Rajput”); //set the user name
        user.setVehicle(vehicle); //set the vehicle entity to the field of the user entity i.e. vehicle entity inside the user entity
       
        SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); //create session factory object
        Session session = sessionFactory.openSession(); //create the session object
        session.beginTransaction();//create the transaction from the session object
        
        session.save(vehicle); // save the vehicle entity to the database
        session.save(user); // save the user entity to the database
        
        session.getTransaction().commit(); //close the transaction
        session.close(); //close the session
    }
}

OUTPUT: 
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into VEHICLE (VEHICLE_NAME) values (?)
Hibernate: insert into USER (USER_NAME, VEHICLE_ID) values (?, ?)

Mapping in Hibernate

Now we look the created tables for that.

Output for Mapping in Hibernate

In Next Chapter we will discuss about One to Many Mapping.

              <<Previous Chapter 16<<    >>Next Chapter18>>