Newsletter

Hibernate One to One Mapping Example

Hibernate » on Aug 1, 2011 { 13 Comments } By Sivateja

Let us see few points regarding this one to one mapping..

  • One object is associated with one object only
  • In this relationship, one object of the one pojo class contains association with one object of the another pojo class
  • To apply one to one relationship between two pojo class objects it is possible by without taking a separate foreign key column in the child table of the database
  • To apply one to one relationship, we copy the primary key value of parent object into primary key value of the child object.  So that the relationship between two objects is one to one
  • If we want to copy parent object primary key value into child object primary key, we need to use a special generator class given by hibernate called foreign
  • Actually this foreign generator is only used in one to one relationship only
  • We are going to apply one to one between student and address pojo classes, here the relation is one address is assigned for one student only
  • In order to get one to one relationship between student and address, we are copying primary key value of student into primary key value of address

Example…..

files required…

  • Student.java
  • Address.java
  • Address.hbm.xml
  • Student.hbm.xml
  • OurLogic.java
  • hibernate.cfg.xml

Student.java

package str;

public class Student {

	private int studentId;
	private String studentName;

	public int getStudentId() {
		return studentId;
	}
	public void setStudentId(int studentId) {
		this.studentId = studentId;
	}
	public String getStudentName() {
		return studentName;
	}
	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}

}

Address.java

package str;
public class Address {

	private int addressId;
	private String city;
	private String state;
	private Student s;	

	public Student getS() {
		return s;
	}
	public void setS(Student s) {
		this.s = s;
	}
	public int getAddressId() {
		return addressId;
	}
	public void setAddressId(int addressId) {
		this.addressId = addressId;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}

}

Address.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="str.Address" table="address">

<id name="addressId" column="addressid" >
<generator>
<param name="property">s</param>
</generator>
</id>
<property name="city" column="city" length="10"/>
<property name="state" column="state" length="10"/>

<one-to-one name="s" class="str.Student" cascade="all" />

</class>
</hibernate-mapping>

Student.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="str.Student" table="student">

<id name="studentId" column="studentid"  />
<property name="studentName" column="studentname" length="10"/>

</class>
</hibernate-mapping>

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>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">admin</property>

<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>

<mapping resource="Student.hbm.xml"></mapping>
<mapping resource="Address.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>

OurLogic.java

package str;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class OurLogic {

	public static void main(String args[])
	{

		Configuration cfg = new Configuration();
		cfg.configure("hibernate.cfg.xml"); 

		SessionFactory factory = cfg.buildSessionFactory();
		Session session = factory.openSession();		

		Student s=new Student();
		s.setStudentId(100);
		s.setStudentName("java4s");

		Address ad = new Address();
		ad.setAddressId(509);
		ad.setCity("Carry");
		ad.setState("NC");
		ad.setS(s);		

		    Transaction tx = session.beginTransaction();

		              session.save(ad);

		    tx.commit();

		    session.close();
		    System.out.println("One to One is Done..!!");
		    factory.close();

	}
}

Output:

Let us see by loading the object form the database whether the one to one is working fine or not…

OurLogic_loading.java

package str;

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

public class OurLogic_loading {

	public static void main(String args[])
	{

		Configuration cfg = new Configuration();
		cfg.configure("hibernate.cfg.xml"); 

		SessionFactory factory = cfg.buildSessionFactory();
		Session session = factory.openSession();		

        Object o = session.get(Address.class, new Integer(100));
        Address a = (Address)o;
        System.out.println(a.getCity());

        Student s=a.getS();
        System.out.println(s.getStudentName());

		    session.close();
		    System.out.println("One to One is Done..!!");
		    factory.close();

	}
}

Output

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

13 Responses to “Hibernate One to One Mapping Example”
  1. Mohammed Vaseem says:

    Hello,
    I got a big confusion in this program. what is the purpose of lines 10,11,2 in Address.hbm.xml files in this code.
    Please provide explaination to this program.
    Thanks in advance.

  2. MohanReddy says:

    Hi Admin,

    As Mohammed i got same doubt, what is the use of “10,11,12 in Address.hbm.xml” file
    2. in OurLogic.java class what is the use of below line.
    ad.setAddressId(509);

  3. naveen says:

    please mention class=”foreign” in generator class in Address.hbm.xml…otherwise you get some error…..i done…..

  4. king says:

    dear the programm you have zipped is many-many,can you please add one to one application

  5. naag says:

    please explain 10,11,12 lines in Address.hbm.xml

  6. rajgopal says:

    column=”studentname” but in screenshot it is studentnam ?
    I was creating table by looking at screenshots so was getting error
    but still I really like java4s.com 😉

  7. Ganesh says:

    Dear Sir,

    I am Java Developer.
    Your website is very nice for student and Developer also.
    Sir can you please provide all Hibernate Example using anotaion .

    If possible please help me doing this.

    Thanks …..

    Ganesh ….!

  8. raghava says:

    hi siva ,
    can u please clarify line no 24
    ad.setAddressId(509)
    why?
    whats need?

  9. kamorudeen says:

    thanks so much for this example it help……………you guys asking question should register for a java class,it will help you….in case you need an answer those number 10,10 are the size of the word you will enter in byte code…why the address 509,is the id in the table in data bass…register for a java class fast!!!

  10. Ramesh says:

    Really below code so confusing.
    I can see, so many has the same doubts, can any one clarify on this. even attached source code also wrong code.

    Address.hbm.xml — 10,11,12
    OurLogic.java — 24

  11. YARRAMASU TRINADH says:

    you said about a foreign key in generator class see in one-to-one, there is no representation of foreign in a generator class

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.