package ManyToMany;
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;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
@Entity
@Table(name="t_student",catalog="exam")
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Column(name="s_name",length=20)
private String name;
@ManyToMany(targetEntity=Teacher.class)
//使用joinTable描述中间表,并描述表中外键与Student,Teacher的映射关系
//JoininColumn描述Student与中间表的映射关系,referencedColumnName表示映射的外键,默认是主键
//inverseJoinColumns描述Teacher与中间表的映射关系
@JoinTable(name="s_t",joinColumns={@JoinColumn(name="c_student_id",referencedColumnName="id")},
inverseJoinColumns={@JoinColumn(name="c_teacher_id",referencedColumnName="id")})
@Cascade(CascadeType.SAVE_UPDATE)
private Set<Teacher> teachers=new HashSet<Teacher>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Teacher> getTeachers() {
return teachers;
}
public void setTeachers(Set<Teacher> teachers) {
this.teachers = teachers;
}
}
***********************配置文件的方法
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="ManyToMany.Student" table="t_student">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="name" column="name"/>
<set name="teachers" table="t_teacher_student" cascade="save-update">
<key column="student_id"></key>
<many-to-many class="ManyToMany.Teacher" column="teacher_id" />
</set>
</class>
</hibernate-mapping>
(不建议实用)***************************