Many to Many in Hibernate 4


Hôm nay mình giới thiệu các bạn vể việc O/R mapping from mối quan hệ nhiều nhiều trong database to Object java của chúng ta.

Source code : download.

Hình ảnh database :

d1

Cấu trúc thư mục của chúng ta như sau :

d1

Class Course.java


package thaihoanghai.hibernate.bean;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name = "course")
public class Course {
 @Id
 @Column(name = "course_id")
 @GeneratedValue
 private Long courseId;

@Column(name = "course_name")
 private String courseName;

@ManyToMany(mappedBy="courses")
 private Set<Student> students = new HashSet<Student>();

public Course() {
 }

public Course(String courseName) {
 this.courseName = courseName;
 }

public Set<Student> getStudents() {
 return students;
 }

public void setStudents(Set<Student> students) {
 this.students = students;
 }

public Long getCourseId() {
 return courseId;
 }

public void setCourseId(Long courseId) {
 this.courseId = courseId;
 }

public String getCourseName() {
 return courseName;
 }

public void setCourseName(String courseName) {
 this.courseName = courseName;
 }
}

Class Student,java


package thaihoanghai.hibernate.bean;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name="student")
public class Student {
 @Id
 @Column(name="student_id")
 @GeneratedValue
 private Long studentId;

@Column(name="student_name")
 private String studentName ;

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

public Student() {
 }

public Long getStudentId() {
 return studentId;
 }

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

public String getStudentName() {
 return studentName;
 }

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

@ManyToMany(cascade = {CascadeType.ALL})
 @JoinTable(name="student_course",joinColumns={@JoinColumn(name="student_id")},inverseJoinColumns={@JoinColumn(name="course_id")})
 private Set<Course> courses = new HashSet<Course>();

public Set<Course> getCourses() {
 return courses;
 }

public void setCourses(Set<Course> courses) {
 this.courses = courses;
 }
}

Class StudentCourseDAO.java


package thaihoanghai.hibernate.dao;

import java.util.Set;

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

import thaihoanghai.hibernate.bean.Course;
import thaihoanghai.hibernate.bean.Student;
import thaihoanghai.hibernate.util.HibernateUtil;

public class StudentCourseDAO {

 public boolean addOneStudent(Student sutudent, Course course){
 boolean flag = false;
 Transaction trns = null;
 Session session = HibernateUtil.getSeesionfactory().openSession();

 try {
 trns = session.beginTransaction();
 sutudent.getCourses().add(course);
 session.save(sutudent);
 trns.commit();
 flag = true;

} catch (Exception e) {
 System.out.println("Co vao day");
 if(trns != null)
 trns.rollback();

 System.out.println("BUG : "+e.toString());
 }finally{

 session.flush();
 session.close();
 }
 return flag;

 }

 public boolean addAllStudent(Set<Student> sutudents, Course course){
 boolean flag = false;
 Transaction trns = null;
 Session session = HibernateUtil.getSeesionfactory().openSession();

 try {
 trns = session.beginTransaction();
 for(Student s : sutudents){
 s.getCourses().add(course);
 session.save(s);
 }

 trns.commit();
 flag = true;

} catch (Exception e) {
 if(trns != null)
 trns.rollback();
 System.out.println("BUG : "+e.toString());
 }finally{
 session.flush();
 session.close();
 }
 return flag;

 }
}

Class StudentCourseService.java


package thaihoanghai.hibernate.service;

import java.util.Set;

import thaihoanghai.hibernate.bean.Course;
import thaihoanghai.hibernate.bean.Student;
import thaihoanghai.hibernate.dao.StudentCourseDAO;

public class StudentCourseService {

 StudentCourseDAO scDAO = new StudentCourseDAO();

 public boolean addOneStudent(Student std, Course cou){
 return scDAO.addOneStudent(std, cou);
 }

 public boolean addAllStudent(Set<Student> students, Course course){
 return scDAO.addAllStudent(students, course);
 }
}

class HibernateUtil.java


package thaihoanghai.hibernate.util;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * Hibernate Util used to configure Hibernate's Session Factoru and retrieve it as Singleton
 * @author kobee
 *
 */
public class HibernateUtil {
 private static final SessionFactory seesionFactory;
 private static ServiceRegistry serviceRegistry;

 static{
 try {
 Configuration configuration = new Configuration();
 configuration.configure();
 serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
 seesionFactory = configuration.buildSessionFactory(serviceRegistry);

 } catch (HibernateException e) {
 System.err.println("Initial SessionFactoru creation failed. " + e);
 throw new ExceptionInInitializerError(e);
 }

 }

public static SessionFactory getSeesionfactory() {
 return seesionFactory;
 }

}

File hibernate.config.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://localhost/mydatabase</property>
 <property name="hibernate.connection.username">root</property>
 <property name="hibernate.connection.password">123456</property>
 <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

 <!-- JDBC connecition pool (use the built-in) -->
 <property name="hibernate.connection.pool_size">1</property>
 <!-- Enable Hibernate's automatic session context management -->
 <property name="hibernate.current_session_context_class">thread</property>

 <!-- Echo all executed SQL to stdout -->
 <property name="show_sql">true</property>
 <property name="format_sql">false</property>
 <property name="hbm2ddl.auto">Validate</property>

 <!-- Mapping to Resource -->
 <mapping class="thaihoanghai.hibernate.bean.Student"/>
 <mapping class="thaihoanghai.hibernate.bean.Course"/>

</session-factory>
</hibernate-configuration>

Class Test.java


package my_project;

import java.util.HashSet;
import java.util.Set;

import thaihoanghai.hibernate.bean.Course;
import thaihoanghai.hibernate.bean.Student;
import thaihoanghai.hibernate.service.StudentCourseService;

public class Test {

 public static void main(String[] args) {

 StudentCourseService service= new StudentCourseService();
 // Add one student into the course
 Student student1 = new Student("Kobee");
 Course course1 = new Course("NCTH4A");
 service.addOneStudent(student1, course1);

 // Acc more student into class the course

 Course course2 = new Course("NCTH5A");
 Student student2 = new Student("Jenny");
 Student student3 = new Student("Ducky");;
 Student student4 = new Student("Justina");
 Set<Student> studentList = new HashSet<Student>();
 studentList.add(student2);
 studentList.add(student3);
 studentList.add(student4);

 service.addAllStudent(studentList, course2);

 }
}

Kết quả của chạy test trên :

Student table:

d1Course table     d2 student_course d3

ok chúc các bạn thành công .

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: