Hibernate 5-bidirectional association-many-to-many (n:n)

Keywords: Java Hibernate xml Session Database

1. Create a project with the name hibernatedemo 15 and the directory structure as shown in the figure.


2. Create a lib directory in the project to store jar files. The directory structure is shown in the figure.


3. Create the entity class Course, package name (com.mycompany.demo.bean) in the src directory, as shown in the figure


4. The content of the entity class Course is as follows

package com.mycompany.demo.bean;

import java.util.Set;

public class Course {
	private int cid;
	private String name;
	private Set<Student> students;
	public Set<Student> getStudents() {
		return students;
	}
	public void setStudents(Set<Student> students) {
		this.students = students;
	}
	public Course() {
		super();
	}
	public Course(String name) {
		super();
		this.name = name;
	}
	public int getCid() {
		return cid;
	}
	public void setCid(int cid) {
		this.cid = cid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}


5. Create the mapping file Course.hbm.xml and package name (com.mycompany.demo.bean) of the entity class Course in the src directory, as shown in the figure.


6. The mapping file Course.hbm.xml is as follows

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<!--
	package:Appoint<class/>Where is the bag 
 -->
<hibernate-mapping package="com.mycompany.demo.bean">
	<!--
		name:Class name
		table:Table Name 
		catalog:Database name,Default is hibernate.cfg.xml The name of the database configured in
	 -->
   <class name="Course" table="course">
      <meta attribute="class-description">
         This class contains the course detail. 
      </meta>
      <!--
      	name:Property name
      	colum:Column Name 
       -->
      <id name="cid" type="int" column="cid">
      		<!--
      			increment:hibernate Maintaining primary key values
      			identity:Database self-growth
      			sequence:sequence
      			native:Select generation strategies based on different databases
      			uuid:adopt UUID Algorithmic Generation,More practical use
      			assigned:Manual settings
      		 -->
         <generator class="native"/>
      </id>
      
      <!--
      	length:Byte length
      	type:Field type,Support java and hibernate type
      	not-null:Non-empty constraints
      	unique:Uniqueness constraints
       -->
      <property name="name" column="name" />
      
      <set name="students" table="student_course" cascade="save-update">
      	<key column="cid"/>
      	<many-to-many class="Student" column="sid"></many-to-many>
      </set>
   </class>
</hibernate-mapping>


7. Create the entity class Student, package name (com.mycompany.demo.bean) in the src directory, as shown in the figure


8. The content of the entity class Student is as follows

package com.mycompany.demo.bean;

import java.util.Set;


public class Student {
	private int sid;
	private String name;
	private Set<Course> courses;
	public Student() {
		super();
	}
	public Student(String name) {
		super();
		this.name = name;
	}
	public int getSid() {
		return sid;
	}
	public void setSid(int sid) {
		this.sid = sid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Set<Course> getCourses() {
		return courses;
	}
	public void setCourses(Set<Course> courses) {
		this.courses = courses;
	}
}


9. Create the mapping file Student.hbm.xml, package name (com.mycompany.demo.bean) of the entity class Student in the src directory, as shown in the figure.


10. The mapping file Student.hbm.xml is as follows

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<!--
	package:Appoint<class/>Where is the bag 
 -->
<hibernate-mapping package="com.mycompany.demo.bean">
	<!--
		name:Class name
		table:Table Name 
		catalog:Database name,Default is hibernate.cfg.xml The name of the database configured in
	 -->
   <class name="Student" table="student">
      <meta attribute="class-description">
         This class contains the student detail. 
      </meta>
      <!--
      	name:Property name
      	colum:Column Name 
       -->
      <id name="sid" type="int" column="sid">
      		<!--
      			increment:hibernate Maintaining primary key values
      			identity:Database self-growth
      			sequence:sequence
      			native:Select generation strategies based on different databases
      			uuid:adopt UUID Algorithmic Generation,More practical use
      			assigned:Manual settings
      		 -->
         <generator class="native"/>
      </id>
      
      <!--
      	length:Byte length
      	type:Field type,Support java and hibernate type
      	not-null:Non-empty constraints
      	unique:Uniqueness constraints
       -->
      <property name="name" column="name" type="string" length="50" not-null="true" unique="false"/>
      
      <set name="courses" table="student_course" cascade="save-update">
      	<key column="sid"></key>
      	<many-to-many class="Course" column="cid"></many-to-many>
      </set>
   </class>
</hibernate-mapping>


11. Create the tool class HbnUtil in the src directory with the package name (com.mycompany.demo.util), as shown in the figure.


12. The tool class HbnUtil is as follows

package com.mycompany.demo.util;

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

public class HbnUtil {
	private static SessionFactory sessionFactory;
	
	public static Session getSession(){
		if(sessionFactory == null || sessionFactory.isClosed()){
			sessionFactory = new Configuration().configure().buildSessionFactory();
		}
		
		return sessionFactory.getCurrentSession();
	}
}


13. Create Hibernate configuration file hibernate.cfg.xml in the src directory, as shown in the figure


14.Hibernate's configuration file, hibernate.cfg.xml, reads as follows

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
   <session-factory>
   		<!-- dialect,From Hibernate core jar(hibernate-core-x.x.x.Finall.jar)
   		In the document or.hibernate.dialect Find the corresponding class in the package,The full name of a class is -->
	   <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
	   <!-- drive -->
	   <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
	
	   <!-- Database Connection Address -->
	   <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
	   <!-- User name -->
	   <property name="hibernate.connection.username">
	      root
	   </property>
	   <!-- Password -->
	   <property name="hibernate.connection.password"></property>
	   <!--
	   		create:Every time it's created,Delete if it exists
	   		create-drop:Create a new table,sessionFactory Close,The table will be deleted
	   		update :Table field addition,Synchronization,Field Reduction Asynchronism,Data changes are synchronized
	    -->
	   <property name="hibernate.hbm2ddl.auto">update</property>
	   <!-- output sql -->
	   <property name="hibernate.show_sql">true</property>
	   <!-- Format sql -->
	   <property name="hibernate.format_sql">true</property>
	   <!-- Transaction environment A thread to a transaction
	   		thread:Local transaction environment
	   		jta:Distributed Transaction Environment
	   		SpringSessionContext:Be used for ssh integration
	    -->
	   <property name="hibernate.current_session_context_class">thread</property>	  
	   
	   <!-- Use c3p0 data source -->
	   <property name="hibernate.connection.provider_class">
	   org.hibernate.c3p0.internal.C3P0ConnectionProvider</property> 
	
	   <!-- List of XML mapping files -->
	   <mapping resource="com/mycompany/demo/bean/Course.hbm.xml"/>
	   <mapping resource="com/mycompany/demo/bean/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>


15. Create a test directory in the project to store test files, the file name TestApp, the package name (com.mycompany.demo.bean), and the directory structure is shown in the figure.


16. The TestApp test class is as follows

package com.mycompany.demo.bean;

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

import org.hibernate.Session;
import org.junit.Before;
import org.junit.Test;

import com.mycompany.demo.util.HbnUtil;

public class TestApp {
	
	private Session session;
	
	@Before
	public void init(){
		session = HbnUtil.getSession();
	}
	
	/*
	 * Bidirectional association-many-to-many (n:n)
	 */
	@Test
	public void testManyToMany(){
		try {
			session.beginTransaction();
			
			Course course1 = new Course("maven");
			
			Student student = new Student("xiaoxiao");

			Set<Student> students = new HashSet<Student>();
			students.add(student);
			
			course1.setStudents(students);
			
			session.save(course1);
			
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			e.printStackTrace();
		}
	}
}

Posted by whit3fir3 on Thu, 14 Feb 2019 03:18:19 -0800