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 make many-to-one mapping in java with Hibernate

In this article we will see how to create an many-to-one mapping techniques in hibernate framework.

Mapping are of following 4 types in hibernate :

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

We will explain this with the help of an example:

We will make two class Student(We named the class Stu2 but we will reference it as Student to make it more easy to understand) and FavouriteMovie. Multiple student can have unique FavouriteMovie so there is a many to one dependency among them.

Listing 1: FavouriteMovie class

package model;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

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

    @Id
    @GeneratedValue
    @Column(name = "M_ID")
    private Long id;
    private String name;
    private int year;

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public FavouriteMovie() {
    }

    public Long getId() {
        return id;
    }

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

    public FavouriteMovie(String n, int yr) {
        name = n;
        year = yr;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
} 
  • We defined a class FavouriteMovie with fields like id, name, year.
  • We define the setter and getter function for these
  • We set the id to be auto generated and also we set the name for this column to be M_ID

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.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.ManyToOne;

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

    private Long id;
    private String name;
    private FavouriteMovie m;

    public Stu2(String n, FavouriteMovie f) {
        name = n;
        m = f;
    }
    public Stu2() {
    }
    @Id
    @GeneratedValue
    @Column(name = "STUDENT_ID")
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    @ManyToOne(cascade = CascadeType.ALL)
    public FavouriteMovie getM() {
        return m;
    }
    public void setM(FavouriteMovie m) {
        this.m = m;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
  • We made a student class with fields like id ,name. We also made a variable m which can contain favorite movie.
  • We made setter and getter function for each field.
  • We used @Id and @GeneratedValue because we will use the field id as a primary key and its value will be auto generated.
  • For implementing many to one mapping we use @ManyToOne(cascade = CascadeType.ALL).

Now we will 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.Stu2"/>
        <mapping class="model.FavouriteMovie"/>
    </session-factory>
</hibernate-configuration>
 
  • We defined the configuration parameter for the database.
  • We also defined the mapping class for both the classes.

Now we will 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 will make a class which will make this all work:

Listing 5: App2 class

package Main;
/**
 * * @author Anurag
 */
import model.FavouriteMovie;
import model.Stu2;
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();
        FavouriteMovie f = new FavouriteMovie("Terminator", 2011);
        Stu2 s1 = new Stu2("Anurag", f);
        Stu2 s2 = new Stu2("xyz", f);
        s.save(s1);
        s.save(s2);
        tx.commit();
    }
}
  • Firstly, We made a session instance with help of session factory object.
  • Now we start the transaction and made an object for favorite movie.
  • Now we make two student object and set the value such that both student have the same favorite movie.
  • We save the session and commit the transaction to make the changes permanent
  • When the program is run then two table named Stu2, FavouriteMovie are made and the student record have many to one dependency on the FavouriteMovie table.Actually a field will be added in student (stu2) table which will contain the id of the favorite movie for this particular Student.

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