Hibernate framework-06-01-Many-to-many association mapping


Entity many-to-many association

Insert picture description here

In the course selection system of a university, a student can take multiple courses at the same time, and a course can be taken by several students. How should such a many-to-many relationship be realized?

Insert picture description here

Database many-to-many association

In order to express a many-to-many relationship, an intermediate table needs to be created.

Insert picture description here

Insert picture description here

Insert picture description here

xml format configuration

Project structure

Insert picture description here

Course.java

package com.hibernate.entity;

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

public class Course {
    
    

	private Integer id;
	private String courseName;
	private int credit;//学分
	
	//与Student之间的多对多
	private Set students = new HashSet<>();

	public Integer getId() {
    
    
		return id;
	}

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

	public String getCourseName() {
    
    
		return courseName;
	}

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

	public int getCredit() {
    
    
		return credit;
	}

	public void setCredit(int credit) {
    
    
		this.credit = credit;
	}

	public Set getStudents() {
    
    
		return students;
	}

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

	@Override
	public String toString() {
    
    
		return "Course [id=" + id + ", courseName=" + courseName + ", credit=" + credit + ", students=" + students
				+ "]";
	}
	
	
}

Student.java

package com.hibernate.entity;

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

public class Student {
    
    

	private Integer id;
	private String stuName;
	private String stuNo;
	
	private Set courses = new HashSet<>();//直接初始化,防止空引用异常

	public Integer getId() {
    
    
		return id;
	}

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

	public String getStuName() {
    
    
		return stuName;
	}

	public void setStuName(String stuName) {
    
    
		this.stuName = stuName;
	}

	public String getStuNo() {
    
    
		return stuNo;
	}

	public void setStuNo(String stuNo) {
    
    
		this.stuNo = stuNo;
	}

	public Set getCourses() {
    
    
		return courses;
	}

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

	@Override
	public String toString() {
    
    
		return "Student [id=" + id + ", stuName=" + stuName + ", stuNo=" + stuNo + ", courses=" + courses + "]";
	}
	
	
}

Course.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.hibernate.entity">
    <class name="Course" table="hibernate_06_01_course">
        <id name="id" type="int" column="id">
            <generator class="identity"></generator>
        </id>
        <property name="courseName" column="COURSE_NAME" ></property>
        <property name="credit"/>
        
        <!-- 映射Course与Student之间的多对多关系
        	set用来映射Set类型的属性
        	table:指定中间表表名
        	key:指定外键字段名字(在中间表中参照当前实体类对应表)
        	many-to-many表示多对多关系 column="COURSE_ID"(指定中间表中参照关联类型对应表的外键)
        	inverse="true"放弃维护关联关系(Course作为被控方) -->
        <set name="students" table="hibernate_06_01_student_course" inverse="true">
        	<key column="COURSE_ID"/>
        	<many-to-many class="Student" column="STU_ID"/>
        </set>
    </class>
</hibernate-mapping>

Student.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.hibernate.entity">
    <class name="Student" table="hibernate_06_01_studnet">
        <id name="id" type="int" column="id">
            <generator class="identity"></generator>
        </id>
        <property name="stuName" column="STU_NAME" ></property>
        <property name="stuNo" column="STU_NO"/>
        
        <!-- 映射Student与Course之间的多对多关系
        	set用来映射Set类型的属性
        	table:指定中间表表名
        	key:指定外键字段名字(在中间表中参照当前实体类对应表)
        	many-to-many表示多对多关系 column="COURSE_ID"(指定中间表中参照关联类型对应表的外键) -->
        <set name="courses" table="hibernate_06_01_student_course" >
        	<key column="STU_ID"/>
        	<!-- 配置另一个外键 -->
        	<many-to-many class="Course" column="COURSE_ID"/>
        </set>
    </class>
</hibernate-mapping>

Test.java

package com.hibernate.ui;

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

import com.hibernate.entity.Course;
import com.hibernate.entity.Student;
import com.hibernate.util.HibernateUtil;

public class Test {
    
    

	public static void main(String[] args) {
    
    
		save();
		
		HibernateUtil.closeSessionFactory();
	}

	//保存学生和课程
	private static void save() {
    
    
		Session session = HibernateUtil.openSession();
		Transaction tx = session.beginTransaction();
		
		Student stu = new Student();
		stu.setStuName("张三");
		stu.setStuNo("2018011000");
		
		Course cou = new Course();
		cou.setCourseName("Android基础编程");
		cou.setCredit(4);
		
		//建立关联
		stu.getCourses().add(cou);
		//当Course作为被控方时,即便程序中修改了Course对象关联的学生,也不会去修改中间表
		//修改包括插入与删除
		cou.getStudents().add(stu);
		
		session.save(stu);
		session.save(cou);
		
		tx.commit();
		session.close();
	}
}







Annotation format configuration

Insert picture description here

Insert picture description here

Project structure

Insert picture description here

Course.java

package com.hibernate.entity;

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

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

@Entity
@Table(name="hibernate_06_01_course")
public class Course {
    
    

	private Integer id;
	private String courseName;
	private int credit;//学分
	
	//与Student之间的多对多
	private Set students = new HashSet<>();

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)//identity室友数据库决定的
	public Integer getId() {
    
    
		return id;
	}

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

	@Column(name="course_name")
	public String getCourseName() {
    
    
		return courseName;
	}

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

	public int getCredit() {
    
    
		return credit;
	}

	public void setCredit(int credit) {
    
    
		this.credit = credit;
	}

	//为了判断集合中对象的类型
	@ManyToMany(mappedBy="courses",targetEntity=Student.class)
	public Set getStudents() {
    
    
		return students;
	}

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

	@Override
	public String toString() {
    
    
		return "Course [id=" + id + ", courseName=" + courseName + ", credit=" + credit + ", students=" + students
				+ "]";
	}
}

Student.java

package com.hibernate.entity;

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

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

@Entity
@Table(name="hibernate_06_01_studnet")
public class Student {
    
    

	private Integer id;
	private String stuName;
	private String stuNo;
	
	private Set<Course> courses = new HashSet<>();

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	public Integer getId() {
    
    
		return id;
	}

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

	@Column(name="STU_NAME")
	public String getStuName() {
    
    
		return stuName;
	}

	public void setStuName(String stuName) {
    
    
		this.stuName = stuName;
	}

	@Column(name="STU_NO")
	public String getStuNo() {
    
    
		return stuNo;
	}

	public void setStuNo(String stuNo) {
    
    
		this.stuNo = stuNo;
	}

	@ManyToMany//映射多对多关系
	//映射中间表
	//name=中间表表明
	//joinColumns=外键字段
	//inverseJoinColumns
	@JoinTable(name="hibernate_06_01_student_course",
	    joinColumns=@JoinColumn(name="STU_ID"),
	    inverseJoinColumns=@JoinColumn(name="COURSE_ID"))
	public Set<Course> getCourses() {
    
    
		return courses;
	}
	//这里和上面的定义时候加上课泛型,可以省略targerEntity标签
	
	
	

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

	@Override
	public String toString() {
    
    
		return "Student [id=" + id + ", stuName=" + stuName + ", stuNo=" + stuNo + ", courses=" + courses + "]";
	}
}

Guess you like

Origin blog.csdn.net/qq_44627608/article/details/115180644