标签:des style blog ar io color os sp for
1 package com.hb.model; 2 3 import java.util.HashSet; 4 import java.util.Set; 5 6 import javax.persistence.Entity; 7 import javax.persistence.GeneratedValue; 8 import javax.persistence.Id; 9 import javax.persistence.ManyToMany; 10 import javax.persistence.Table; 11 12 @Entity 13 @Table(name="t_teacher") 14 public class Teacher { 15 private int tid ; 16 private String tname; 17 private Set<Student> students = new HashSet<Student>(); 18 19 @Id 20 @GeneratedValue 21 public int getTid() { 22 return tid; 23 } 24 public void setTid(int tid) { 25 this.tid = tid; 26 } 27 public String getTname() { 28 return tname; 29 } 30 public void setTname(String tname) { 31 this.tname = tname; 32 } 33 @ManyToMany 34 public Set<Student> getStudents() { 35 return students; 36 } 37 public void setStudents(Set<Student> students) { 38 this.students = students; 39 } 40 41 42 43 }
package com.hb.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="t_student") public class Student { private int sid; private String sname; @Id @GeneratedValue public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } }
生成的表如下:
这样生成的中间表的名称是自动生成的,也可以通过加入一些属性改变表的名称
只需要在Teacher类里面添加一些属性,修改后的代码如下:
1 @Entity 2 @Table(name="t_teacher") 3 public class Teacher { 4 private int tid ; 5 private String tname; 6 private Set<Student> students = new HashSet<Student>(); 7 8 @Id 9 @GeneratedValue 10 public int getTid() { 11 return tid; 12 } 13 public void setTid(int tid) { 14 this.tid = tid; 15 } 16 public String getTname() { 17 return tname; 18 } 19 public void setTname(String tname) { 20 this.tname = tname; 21 } 22 @ManyToMany 23 @JoinTable(name="t_s", //表名 24 joinColumns={ @JoinColumn(name="teacher_id")}, // ??? 25 inverseJoinColumns={@JoinColumn(name="student_id")} // 对方那张表的对应的外键的id 26 ) 27 public Set<Student> getStudents() { 28 return students; 29 } 30 public void setStudents(Set<Student> students) { 31 this.students = students; 32 } 33 }
多对多单向关联在xml文件中的配置
1 <hibernate-mapping> 2 <class name="com.hb.model.Teacher"> 3 <id name="tid"> 4 <generator class="native"></generator> 5 </id> 6 7 <property name="tname"></property> 8 <set name="students" table="t_s"> 9 <key column="teacher_id"></key> 10 <many-to-many class="com.hb.model.Student" column="student_id"/> 11 </set> 12 </class> 13 14 </hibernate-mapping>
标签:des style blog ar io color os sp for
原文地址:http://www.cnblogs.com/Mokaffe/p/4158536.html