Master java skills

Hibernate one-to-many mapping

In this tutorial, we will learn how to map one-to-many mapping using hibernate. Let’s consider There is a Doctor class and one doctor has many clinics and thus many clinic addresses.

pom 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 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 Doctor class

package com.javatrainingschool;

import java.util.List;

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


@Entity
@Table(name = "doctor_1")
public class Doctor {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;
	private String name;
	
	@OneToMany(cascade = CascadeType.ALL)
	@JoinColumn(name = "doc_id")
	private List<Address> clinicAddresses;

	//getter and setter methods
	//constructors
}

Create Address 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;

	//getter and setter methods
	//constructors
}

Create hibernate mapping file

<?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="hbm2ddl.auto">update</property>
		<property name="dialect">org.hibernate.dialect.Oracle9iDialect</property>
		<property name="connection.url">jdbc:oracle:thin:@localhost:1521/xepdb1</property>
		<property name="connection.username">singh</property>
		<property name="connection.password">azad</property>
		<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
		<mapping class="com.javatrainingschool.Doctor" />
		<mapping class="com.javatrainingschool.Address" />
	</session-factory>

</hibernate-configuration>

Create main testing class

package com.javatrainingschool;

import java.util.ArrayList;
import java.util.List;

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 DoctorMainTesting {
	
	
	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();    
	        
	    Address add1 = new Address();
	    add1.setAddLine("Clinic Add 1");
	    add1.setCity("Kanpur");
	    add1.setCountry("India");
	    
	    Address add2 = new Address();
	    add2.setAddLine("Clinic Add 2");
	    add2.setCity("Kanpur");
	    add2.setCountry("India");
	    
	    List<Address> addresses = new ArrayList<>();
	    
	    addresses.add(add1);
	    addresses.add(add2);
	    
	    Doctor d1 = new Doctor();
	    d1.setName("Dr Bean");
	    d1.setClinicAddresses(addresses);
	    
	    session.persist(d1);
	    
	    System.out.println("Data saved successfully.");
	    
	    t.commit();
	    session.close();
	    factory.close();
	}
	
}

Verify the tables in the database

Doctor_1 table

Address table