Today, we are going to discuss about one of the mapping techniques in hibernate ie, one to many 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 :
- One to one mapping (Discussed already in previous article)
- One to many mapping
- Many to one mapping
- Many to many mapping
Mapping shows how two entities are related to each other. In one to many mapping one entity of class A can only have a multiple entity in class B. Like for example suppose the two classes are Student and Course. So if this two classes have one to many relationship then it means that one Student can have multiple courses
We will explain this with the help of an example.
We make two class Student and Course. Each student can have multiple courses so there is a one to many dependency among them.
Listing 1: Course 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 Course implements Serializable { @Id @GeneratedValue @Column(name = "C_ID") private Long id; private String name; private int duration; public Course() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Course(String n, int dur) { name = n; duration = dur; } public int getDuration() { return duration; } public void setDuration(int duration) { this.duration = duration; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
- We defined a class Course with fields like id, name, duration.
- 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 C_ID
Listing 2: Student class
package model; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.OneToMany; /** * * @author Anurag */ @Entity public class Stu implements Serializable { private Long id; private String name; private List<Course> c; public Stu() { c = new ArrayList<Course>(); } @Id @GeneratedValue @Column(name = "STUDENT_ID") public Long getId() { return id; } public void setId(Long id) { this.id = id; } @OneToMany(cascade = CascadeType.ALL) @JoinTable(name = "STUDENT_Course", joinColumns = {@JoinColumn(name = "STUDENT_ID")}, inverseJoinColumns = {@JoinColumn(name = "C_ID")}) public List<Course> getC() { return c; } public void setC(List<Course> c) { this.c = c; } 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 c which can contain multiple courses
- 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 one to many mapping we use @OneToMany(cascade = CascadeType.ALL)
- To map the classes a third class would be needed which would contain the mapping between student and course class
- @JoinTable(name = "STUDENT_Course", joinColumns = {@JoinColumn(name = "STUDENT_ID")}, inverseJoinColumns = {@JoinColumn(name = "C_ID")}) - This is used to make a third table named Student_course which will have two columns student_id from the student(stu) class and C_ID from the course class.So if we want that student id 1 has opted for course id 1 and 2 then student_course will have values (1,1) and (1,2).
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.Stu"/> <mapping class="model.Course"/> </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 make a class which will make this all work:
Listing 5: App2 class
package Main; /** * * @author Anurag */ import java.util.ArrayList; import java.util.List; import model.Course; import model.Stu; 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(); Stu s1 = new Stu(); List<Course> c = new ArrayList<Course>(); c.add(new Course("J2EE", 12)); c.add(new Course("Hibernate", 6)); s1.setC(c); s1.setName("Anurag"); s.save(s1); tx.commit(); } }
- Firstly, We made a session instance with help of session factory object.
- Now we start the transaction;
- We made a list type object for course.We fill this object with 2 new courses;
- Now we make a student object and set the value. We set the Course of this student to be the object we just made in previous step.
- We save the session.
- We commit the transaction to make the changes permanent
- When the program is run then three table named Student, Courses, student_course are made and the student record have one to many dependency on the course table.Actually the table student_course will contain the mapping in 2 records having values (1,1) and (1,2).
This is all for today’s article. Hope you liked it. See you next time.