举例:老师和学生
teacher实体
package cn.hibernate.annotationmapping; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.util.HashSet; import java.util.Set; /** * Created by 17921 on 2017/12/31. */ @Entity//将该类声明为一个实体 @Table(name = "Teacher")//指定表的名称 @GenericGenerator(name = "teid",strategy = "native")//创建主键生成策略 public class Teacher { @Id//指定为表的ID @GeneratedValue(generator = "teid")//指定主键生成策略 @Column(name = "tid")//对应数据表的类名 private Integer tid; @Column(name = "tname") private String tname; @ManyToMany//多对多 //中间表 中间表的名称 本实体对应中间表的列 另一个实体对应中间表的列 @JoinTable(name = "RStuTe",joinColumns={@JoinColumn(name = "tid")},inverseJoinColumns = {@JoinColumn(name = "sid")}) private Set<Students> students=new HashSet<Students>(); //省略getset方法 }
Student实体
package cn.hibernate.annotationmapping; import org.hibernate.annotations.*; import org.hibernate.annotations.CascadeType; import javax.naming.Name; import javax.persistence.*; import javax.persistence.Entity; import javax.persistence.Table; import java.util.HashSet; import java.util.Set; /** * Created by 17921 on 2017/12/31. */ @Entity//将该类声明为一个实体 @Table(name = "Students")//指定表的名称 @GenericGenerator(name = "stuid",strategy = "native")//创建主键生成策略 public class Students { @Id//指定为表的ID @GeneratedValue(generator = "stuid")//指定主键生成策略 @Column(name = "sid")//对应数据表的类名 private Integer sid; @Column(name = "sname") private String sname; @ManyToMany()//多对多 @Cascade(value = {CascadeType.SAVE_UPDATE})//级联 //中间表 中间表的名称 本实体对应中间表的列 另一个实体对应中间表的列 @JoinTable(name = "RStuTe",joinColumns = {@JoinColumn(name = "sid")},inverseJoinColumns = {@JoinColumn(name = "tid")}) private Set<Teacher> teachers=new HashSet<Teacher>(); 省略getset方法 }
单测
@Test public void sel(){ Teacher teacher1=new Teacher(); teacher1.setTname("老袁"); Teacher teacher2=new Teacher(); teacher2.setTname("付老师"); Teacher teacher3=new Teacher(); teacher3.setTname("彪哥"); Students students1=new Students(); students1.setSname("老黑"); Students students2=new Students(); students2.setSname("小芮"); Students students3=new Students(); students3.setSname("城余"); students1.getTeachers().add(teacher1); students1.getTeachers().add(teacher2); students2.getTeachers().add(teacher1); students2.getTeachers().add(teacher2); students3.getTeachers().add(teacher1); students3.getTeachers().add(teacher3); Session session = HibernateUtil.getSession(); session.save(students1); session.save(students2); session.save(students3); HibernateUtil.closeSession(); System.out.println("add ok!"); }
结果
student表
teacher表
中间表