Big Data and Hadoop Training @$80 or Rs. 6,000 only - valid till Oct 17th Apply Now!

Hibernate One To Mapping

Ads
 

Hibernate One To Mapping

In this tutorial you will learn, how to do One-to-One mapping using Annotation

In this tutorial you will learn, how to do One-to-One mapping using Annotation

Hibernate One To One Mapping Using Annotation

Hi If you are use-to with the Hibernate annotation, then it is very simple to do mapping using hibernate annotation

Consider a relationship between a Student and a Address, where One Student have only one Address and an Address is related to only one student. Then the Annotation class for the above relationship will be written as,

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

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

	private long studentId;
	private String studentName;
	private Address studentAddress;

	public Student() {
	}

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

	@Id
	@GeneratedValue
	@Column(name = "STUDENT_ID")
	public long getStudentId() {
		return this.studentId;
	}

	public void setStudentId(long studentId) {
		this.studentId = studentId;
	}

	@Column(name = "STUDENT_NAME", nullable = false, length = 100)
	public String getStudentName() {
		return this.studentName;
	}

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

	@OneToOne(cascade = CascadeType.ALL)
	public Address getStudentAddress() {
		return this.studentAddress;
	}

	public void setStudentAddress(Address studentAddress) {
		this.studentAddress = studentAddress;
	}

}

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

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

	private long addressId;
	private String street;
	private String city;
	private String state;
	private String zipcode;
	private Student student;

	public Address() {
	}

	public Address(String street, String city, String state, String zipcode,
			Student student) {
		this.street = street;
		this.city = city;
		this.state = state;
		this.zipcode = zipcode;
		this.student = student;
	}

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

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

	@Column(name = "ADDRESS_STREET", nullable = false, length = 250)
	public String getStreet() {
		return this.street;
	}

	public void setStreet(String street) {
		this.street = street;
	}

	@Column(name = "ADDRESS_CITY", nullable = false, length = 50)
	public String getCity() {
		return this.city;
	}

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

	@Column(name = "ADDRESS_STATE", nullable = false, length = 50)
	public String getState() {
		return this.state;
	}

	public void setState(String state) {
		this.state = state;
	}

	@Column(name = "ADDRESS_ZIPCODE", nullable = false, length = 10)
	public String getZipcode() {
		return this.zipcode;
	}

	public void setZipcode(String zipcode) {
		this.zipcode = zipcode;
	}

	@OneToOne(cascade = CascadeType.ALL)
	public Student getStudent() {
		return student;
	}

	public void setStudent(Student student) {
		this.student = student;
	}
}

Following is the hibernate.cfg.xml file

hibernate.cfg.xml

<?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://192.168.10.13:3306/training1</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</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-drop</property>
		<mapping class="net.roseindia.table.Student" />
		<mapping class="net.roseindia.table.Address" />
	</session-factory>
</hibernate-configuration>

Hibernate util class that reruns the collection

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;
	}
}

Following the sample application file

Main.java

package net.roseindia.app;

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

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

import net.roseindia.util.HibernateUtil;

public class Main {

	public static void main(String[] args) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			Student student = new Student();
			student.setStudentName("John");
			Address address = new Address("B9", "Banglore", "Karnataka",
					"560000", student);
			student.setStudentAddress(address);
			session.save(student);

			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}

	}

}


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


Hibernate: insert into ADDRESS (ADDRESS_CITY, ADDRESS_STATE, ADDRESS_STREET, student_STUDENT_ID, ADDRESS_ZIPCODE) values (?, ?, ?, ?, ?)
Hibernate: insert into STUDENT (studentAddress_ADDRESS_ID, STUDENT_NAME) values (?, ?)
Hibernate: update ADDRESS set ADDRESS_CITY=?, ADDRESS_STATE=?, ADDRESS_STREET=?, student_STUDENT_ID=?, ADDRESS_ZIPCODE=? where ADDRESS_ID=?

Download Select Source Code

Ads

Ads