Hibernate annotation 多对多双向关联(很少用)

双向关联 在认为的 主表 上用到 @JoinTable

 

package com.hibernate.entity;

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

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

@Entity
public class Student implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3543286868313801941L;
	
	private int id;
	
	private String name;
	
	private Set teachers = new HashSet();

	
	@Id
	@GeneratedValue
	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;
	}

	@ManyToMany(mappedBy="students")//students 是 teacher类里的student属性
	public Set getTeachers() {
		return teachers;
	}

	public void setTeachers(Set teachers) {
		this.teachers = teachers;
	}
	
}

 

 

package com.hibernate.entity;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;

@Entity
public class Teacher implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3543286868313801941L;
	
	private int id;
	
	private String name;
	
	private Set students = new HashSet();

	
	@Id
	@GeneratedValue
	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;
	}

	
	@ManyToMany
	@JoinTable(
			    name="s_t",
			    joinColumns=
			        @JoinColumn(name="teacherid", referencedColumnName="id"),//当前表里的id
			    inverseJoinColumns=
			        @JoinColumn(name="studentid", referencedColumnName="id")//与此相对应的表里的id
			    )
	public Set getStudents() {
		return students;
	}

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

 

hibernate.cfg.xml ,ORMappingTest  和之前的一样

你可能感兴趣的:(Hibernate annotation 多对多双向关联(很少用))