Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create an one-to-one mapping in java with Hibernate

This article will discuss about One to one mapping in Java with Hibernate.

Today, we are going to discuss about hibernate one of the mapping techniques in hibernate ie, one to one mapping

Introduction (Hibernate)

Hibernate allows you to map your Java classes to Database Table. We may define it as library, which provide a framework for mapping object oriented model to relational database.

Mapping are of following 4 types in hibernate :

  1. One to one mapping
  2. One to many mapping
  3. Many to one mapping
  4. Many to many mapping

Mapping shows how two entities are related to each other. In one to one mapping one entity of class A can only have a single unique entity in class B. Like for example suppose the two classes are Student and Address. So if this two classes have one to one relationship then it means that one Student can have only one Address.

We will explain this with the help of an example

We make two class Student and Address.Each student can have only one address so there is a one to one dependency among them.

Listing 1: Address class


package model;

import javax.persistence.Entity;
import javax.persistence.Id;

/**
 *
 * @author Anurag
 */
@Entity
public class Address {

    @Id
    private int id;
    private String street;
    private String city;

    public String getCity() {
        return city;
    }

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getStreet() {
        return street;
    }

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

Now we will see what we've done in the code above:

  1. We defined a class Address with fields like street,city and id.
  2. We define the setter and getter function for these.

Listing 2: Student class

package model;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.Serializable;
import javax.persistence.GeneratedValue;
import javax.persistence.OneToOne;

/**
 *
 * @author Anurag
 */
@Entity
public class Student implements Serializable {

    private Long id;
    private String name;
    private Address location;

    @Id
    @GeneratedValue
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @OneToOne(cascade = CascadeType.ALL)
    public Address getLocation() {
        return location;
    }

    public void setLocation(Address location) {
        this.location = location;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Now we will see what we've done in the code above:

  1. We made a student class with fields like id ,name. We also made an object of class Address to store address for this particular student
  2. We made setter and getter function for each field
  3. We used @Id and @GeneratedValue because we will use the field id as a primary key and its value will be auto generated
  4. For Address field we have used @OneToOne(cascade = CascadeType.ALL) to implement one to one mapping on Address field and also used cascading to ensure that if any student record is modified then the address fields gets updated too.

Now we define the configuration file:

Listing 3: 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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernateArt</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">csanurag</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <mapping class="model.Address"/>
        <mapping class="model.Student"/>
    </session-factory>
</hibernate-configuration>

Now we will see what we've done in the code above:

  1. We defined the configuration parameter for the database.
  2. We also defined the mapping class for both the classes.

Now we define the Utility class which will be used to obtain instance of session factory

Listing 4: Utility class

package Main;

/**
 *
 * @author Anurag
 */
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class Utility {

    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {

            throw new ExceptionInInitializerError(ex);
        }
    }

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

Lastly we make a class which will make this all work:

Listing 5: App2 class

package Main;

/**
 *
 * @author Anurag
 */
import model.Address;
import model.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class App2 {

    public static void main(String args[]) {

        SessionFactory sf = Utility.getSessionFactory();
        Session s = sf.getCurrentSession();
        Transaction tx = s.beginTransaction();
        Student s1 = new Student();
        Address a = new Address();
        a.setCity("abc");
        a.setStreet("xyz");
        s1.setName("Anurag");
        s1.setLocation(a);
        s.save(s1);
        tx.commit();
    }
}

Now we will see what we've done in the code above:

  1. Firstly, We made a session instance with help of session factory object.
  2. Now we start the transaction.
  3. We make a Address class object and set some value for the Address.
  4. Now we make a student object and set the value. We set the Address of this student to be the object we just made in previous step.We save the session.
  5. We commit the transaction to make the changes permanent.
  6. When the program is run then two table named Student and Address are made and the student record have one to one dependency on the address table

This is all for today’s article. Hope you liked it. See you next time.



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login