Hibernate annotation 多对多单向关联

 

package com.hibernate.entity;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Student implements Serializable {

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

	
	@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
//	public Set<Teacher> getTeachers() {
//		return teachers;
//	}
//
//	public void setTeachers(Set<Teacher> 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<Student> students = new HashSet<Student>();

	
	@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<Student> getStudents() {
		return students;
	}

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

 hibernate.cfg.xml和ORMappingTest与之前一样,拷过来就可以使用

当然,.xml中要加

<mapping class="com.hibernate.entity.Teacher" />
<mapping class="com.hibernate.entity.Student" />

你可能感兴趣的:(annotation)