Master java skills

Hibernate One-to-One Mapping

In this tutorial, we will learn one-to-one mapping. We will consider that one student will have one address and one address will belong to one student. We will use bidirectional association between student and address.

pom.xml for the project

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sks</groupId>
	<artifactId>HibernateExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>6.0.0.Alpha5</version>
    </dependency>
    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc8</artifactId>
        <version>19.3</version>
    </dependency>
</dependencies>

</project>

Create Student.java class

package com.javatrainingschool;

import javax.persistence.CascadeType;
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.PrimaryKeyJoinColumn;
import javax.persistence.Table;

@Entity
@Table(name = "student")
public class Student {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@PrimaryKeyJoinColumn
	private int id;
	private String name;
	private int age;

	@OneToOne(cascade = CascadeType.ALL)
	@JoinColumn(name = "address")
	private Address address;

	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 int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

}

Create Address.java class

package com.javatrainingschool;

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

@Entity
@Table(name = "address")
public class Address {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int addId;
	private String addLine;
	private String city;
	private String country;

	public String getAddLine() {
		return addLine;
	}

	public void setAddLine(String addLine) {
		this.addLine = addLine;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public int getAddId() {
		return addId;
	}

	public void setAddId(int addId) {
		this.addId = addId;
	}

	@Override
	public String toString() {
		return "Address [addId=" + addId + ", addLine=" + addLine + ", city=" + city + ", country=" + country + "]";
	}

}

Create main testing class OneToOneMain.java

package com.javatrainingschool;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class OneToOneMain {
	
	public static void main(String[] args) {
		
	    StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();  
	    Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
	      
	    SessionFactory factory=meta.getSessionFactoryBuilder().build();  
	    Session session=factory.openSession();  
	      
	    Transaction t=session.beginTransaction(); 
	    
	    
	    Student s = new Student();
	    s.setName("Karn");
	    s.setAge(25);
	    
	    Address add = new Address();
	    add.setAddLine("Line no 10");
	    add.setCity("New Delhi");
	    add.setCountry("India");
	    
	    s.setAddress(add);
	    
	    session.save(add);
	    session.save(s);
	    t.commit();
	    
	    System.out.println("Data persisted successfully.");
	    
	    session.close();
	    factory.close();
	}
}

Hibernate configuration file

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE hibernate-configuration PUBLIC  
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
        
<hibernate-configuration>

<session-factory>
	<property name="hbm2ddl.auto">create</property>
	<property name="dialect">org.hibernate.dialect.OracleDialect</property>
	<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
	<property name="connection.url">jdbc:oracle:thin:@localhost:1521/xepdb1</property>
	<property name="connection.username">singh</property>
	<property name="connection.password">azad</property>
	<mapping class="com.javatrainingschool.Student"/>
	<mapping class="com.javatrainingschool.Address"/>
</session-factory>

</hibernate-configuration>

Database output

Following entries should be created in database tables

Student table
Address table