Hibernate Many One One Mapping

In this tutorial you will learn about hibernate Many To One mapping

Hibernate Many One One Mapping

Hibernate Mapping And Join

Using hibernate we can easily create relationship between two tables. The relationship may be One-To-One, One-To-Many, Many-To-One and Many-To-Many. An Example of One To Many mapping is given below

Address Table

Address.java

package net.roseindia.table;

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

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

	private long addressId;
	private String mohalla;
	private String city;
	private String dist;

	public Address() {
	}

	public Address(String mohalla, String city, String dist) {
		this.mohalla = mohalla;
		this.city = city;
		this.dist = dist;
	}

	@Id
	@GeneratedValue
	@Column(name = "id")
	public long getAddressId() {
		return addressId;
	}

	public void setAddressId(long addressId) {
		this.addressId = addressId;
	}

	@Column(name = "mohalla")
	public String getMohalla() {
		return mohalla;
	}

	public void setMohalla(String mohalla) {
		this.mohalla = mohalla;
	}

	@Column(name = "city")
	public String getCity() {
		return city;
	}

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

	@Column(name = "dist")
	public String getDist() {
		return dist;
	}

	public void setDist(String dist) {
		this.dist = dist;
	}

}

Student Table

Student.java

package net.roseindia.table;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

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

	private long rollNo;
	private String studentName;
	private Address address;

	public Student() {
	}

	public Student(String studentName, Address address) {
		this.studentName = studentName;
		this.address = address;
	}

	@Id
	@GeneratedValue
	@Column(name = "roll_no")
	public long getRollNo() {
		return rollNo;
	}

	public void setRollNo(long rollNo) {
		this.rollNo = rollNo;
	}

	@Column(name = "name")
	public String getStudentName() {
		return studentName;
	}

	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}

	@ManyToOne(cascade = CascadeType.ALL)
	public Address getAddress() {
		return address;
	}

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

Hibernate Connection Util

HibernateUtil.java

package net.roseindia.util;

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

public class HibernateUtil {
	private static final SessionFactory sessionFactory;
	static {
		try {
			sessionFactory = new AnnotationConfiguration().configure()
					.buildSessionFactory();
		} catch (Throwable ex) {
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}

Configuration

SampleInterfaceImp.java

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/student</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password"></property>
		<property name="hibernate.connection.pool_size">10</property>
		<property name="show_sql">true</property>
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="hbm2ddl.auto">create</property>
		
		<mapping class="net.roseindia.table.Student" />
		<mapping class="net.roseindia.table.Address" />
	</session-factory>
</hibernate-configuration>

And Main Class

MyApp.java

package net.roseindia.apps;

import java.util.Iterator;
import java.util.List;

import net.roseindia.table.Address;
import net.roseindia.table.Student;
import net.roseindia.util.HibernateUtil;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class MyApp {

	public static void main(String[] args) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			/*
			 * transaction = session.beginTransaction(); Address address = new
			 * Address("B9", "Rohini", "Delhi");
			 * 
			 * Student ram = new Student("Ram", address); Student syam = new
			 * Student("Syam", address); session.save(ram); session.save(syam);
			 * 
			 * transaction.commit();
			 */

			/* Left Join */
			// String hql = "from Student s left join s.address as obj";

			/* Right Join */
			// String hql = "from Student s Right Join s.address as obj";

			/* Right Join */
			// String hql = "from Student s Inner Join s.address as obj";

			/* Join */
			String hql = "from Student s Join s.address as obj";

			Query query = session.createQuery(hql);
			List lists = query.list();
			Iterator iterator = lists.iterator();
			System.out.println("Name \tRoll \tAddress Id \tAddress");
			while (iterator.hasNext()) {
				System.out.println();
				Object[] objects = (Object[]) iterator.next();
				for (int i = 0; i < objects.length; i++) {
					Object obj = objects[i];
					if (obj instanceof Student) {
						Student s = (Student) obj;
						System.out.print(s.getStudentName() + "\t"
								+ s.getRollNo());
					}
					if (obj instanceof Address) {
						Address a = (Address) obj;
						System.out.print("\t" + a.getAddressId() + "\t"
								+ a.getCity());
					}
				}
			}
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}

	}

}

To run this application at first create a database and configure it the hibernate.cfg.xml file and the uncomment the following im MyApp class

/*
 * transaction = session.beginTransaction(); Address address = new
 * Address("B9", "Rohini", "Delhi");
 * 
 * Student ram = new Student("Ram", address); Student syam = new
 * Student("Syam", address); session.save(ram); session.save(syam);
 * 
 * transaction.commit();
 */

And comment the following

			String hql = "from Student s Join s.address as obj";

			Query query = session.createQuery(hql);
			List lists = query.list();
			Iterator iterator = lists.iterator();
			System.out.println("Name \tRoll \tAddress Id \tAddress");
			while (iterator.hasNext()) {
				System.out.println();
				Object[] objects = (Object[]) iterator.next();
				for (int i = 0; i < objects.length; i++) {
					Object obj = objects[i];
					if (obj instanceof Student) {
						Student s = (Student) obj;
						System.out.print(s.getStudentName() + "\t"
								+ s.getRollNo());
					}
					if (obj instanceof Address) {
						Address a = (Address) obj;
						System.out.print("\t" + a.getAddressId() + "\t"
								+ a.getCity());
					}
				}
			}

after this change to the <property name="hbm2ddl.auto">create</property> to <property name="hbm2ddl.auto">none</property> in hibernate.cfg.xml. And once you get the table and data you just undo in MyApp class or comment the save and run the query.


When you run this application it will display message as shown below:


Hibernate: select student0_.roll_no as roll1_0_0_, address1_.id as id1_1_, student0_.address_id as address3_0_0_, student0_.name as name0_0_, address1_.city as city1_1_, address1_.dist as dist1_1_, address1_.mohalla as mohalla1_1_ from STUDENT student0_ inner join address address1_ on student0_.address_id=address1_.id
Name Roll Address Id Address

Ram 1 1 Rohini
Syam 2 1 Rohini

Download Source Code