Many To Many

import java.io.Serializable;

import javax.persistence.*;

import org.codehaus.jackson.annotate.JsonBackReference;

import java.util.List;


/**
 * The persistent class for the student database table.
 *
 */
@Entity
public class Student implements Serializable {
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Student [id=");
		builder.append(id);
		builder.append(", name=");
		builder.append(name);
		builder.append(", courses=");
		builder.append(courses);
		builder.append("]");
		return builder.toString();
	}

	private static final long serialVersionUID = 1L;

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

	private String name;

	//bi-directional many-to-many association to Course
	@ManyToMany
	@JoinTable(
		name="course_and_student"
		, joinColumns={
			@JoinColumn(name="student_id")  //关系维护端
			}
		, inverseJoinColumns={
			@JoinColumn(name="coruse_id")  //关系被维护端
			},
			uniqueConstraints=@UniqueConstraint(columnNames = { "student_id", "coruse_id"})
		)
	@JsonBackReference   //序列化的时候这儿字段会被忽略
	private List<Course> courses;

	public Student() {
	}

	public Integer getId() {
		return this.id;
	}

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

	public String getName() {
		return this.name;
	}

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

	public List<Course> getCourses() {
		return this.courses;
	}

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


}

import java.io.Serializable;
import java.util.List;

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

import org.codehaus.jackson.annotate.JsonManagedReference;


/**
 * The persistent class for the course database table.
 *
 */
@Entity
public class Course implements Serializable {
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Course [id=");
		builder.append(id);
		builder.append(", name=");
		builder.append(name);
		builder.append("]");
		return builder.toString();
	}

	private static final long serialVersionUID = 1L;

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

	private String name;

	//bi-directional many-to-many association to Student
	@ManyToMany(mappedBy="courses")   //拥有mappedBy属性的实体为关系的被维护端
	@JsonManagedReference
	private List<Student> students;

	public Course() {
	}

	public Integer getId() {
		return this.id;
	}

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

	public String getName() {
		return this.name;
	}

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

	public List<Student> getStudents() {
		return this.students;
	}

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


}




你可能感兴趣的:(Many To Many)