Spring 多对对实体

Posted max-hou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring 多对对实体相关的知识,希望对你有一定的参考价值。

技术图片

 

package com.wangshenghua.entity;

import java.io.Serializable;
import java.util.Set;

import javax.persistence.CascadeType;
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 = "course")
public class Course implements Serializable 

	private static final long serialVersionUID = 5844590076435775458L;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int id;

	private String name;

      /**
      * 一个学生对应多门功课<br>
      * 多对多时,使用中间表关联两者关系<br>
      */

	@ManyToMany(cascade = CascadeType.ALL)
	@JoinTable(name = "student_has_course", 
	joinColumns = @JoinColumn(name = "course_id", 
	referencedColumnName = "id"), 
	inverseJoinColumns = @JoinColumn(name = "student_id", referencedColumnName = "id"))
	private Set<Student> students;

	// @JoinTable里的 name 中间表
	// joinColumns 当前实体ID
	// inverseJoinColumns对方实体ID

	public Course() 
	

	public Course(String name) 
		super();
		this.name = name;
	

	public int getId() 
		return id;
	

	public void setId(int id) 
		this.id = id;
	

	public String getName() 
		return name;
	

	public void setName(String name) 
		this.name = name;
	

	public Set<Student> getStudents() 
		return students;
	

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

	@Override
	public String toString() 
		return "Course [id=" + id + ", name=" + name + ", students=" + students + "]";
	


  

以上是关于Spring 多对对实体的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot中两个实体之间的多对多关系

多对多 Spring MVC mappedBy 引用了一个未知的目标实体属性

Spring数据JPA-休眠多对多关系在链接实体表中插入null

.ef core 多对对关系的关联方法

JPA Spring Boot 微服务 - 使用两个多对一映射持久化实体时的无限循环

Spring Data JPA:查询多对多