hibernate多對多之中間表有多個字段

ame = name;
 }
 @Column(name = "sex")
 public int getSex() {
  return sex;
 }
 public void setSex(int sex) {
  this.sex = sex;
 }
 @OneToMany(mappedBy = "teacher",cascade=CascadeType.ALL)
 public Set<TeacherStudent> getTeacherStudentList() {
  return teacherStudentList;
 }
 public void setTeacherStudentList(Set<TeacherStudent> teacherStudentList) {
  this.teacherStudentList = teacherStudentList;
 }
}

中間表

@Entity
@Table(name = "T_TEACHERSTUDENT")
@SequenceGenerator(name = "SEQ_TEACHERSTUDENT", sequenceName = "SEQ_TEACHERSTUDENT")
public class TeacherStudent implements Serializable {
 private Long id;
 private Student2 student;
 private Teacher2 teacher;
 private String note1;
 private String note2;
 @Id
 @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_TEACHERSTUDENT")
 @Column(name = "ID", nullable = false, precision = 22, scale = 0)
 public Long getId() {
  return id;
 }
 public void setId(Long id) {
  this.id = id;
 }
 @Column(name = "note1")
 public String getNote1() {
  return note1;
 }
 public void setNote1(String note1) {
  this.note1 = note1;
 }
 @Column(name = "note2")
 public String getNote2() {
  return note2;
 }
 public void setNote2(String note2) {
  this.note2 = note2;
 }
 @ManyToOne(cascade=CascadeType.ALL)
 @JoinColumn(name = "student_id", unique = true)
 public Student2 getStudent() {
  return student;
 }
 public void setStudent(Student2 student) {
  this.student = student;
 }
 @ManyToOne
 @JoinColumn(name = "teacher_id", unique = true)
 public Teacher2 getTeacher() {
  return teacher;
 }
 public void setTeacher(Teacher2 teacher) {
  this.teacher = teacher;
 }
}

hibernate.cfg.xml 引入對象

 <mapping class="com.dvn.li.model.Student2"/>
  <mapping class="com.dvn.li.model.Teacher2"/>
  <mapping class="com.dvn.li.model.TeacherStudent"/>

測試:

SessionFactory sessionFactory = null;
  Session session = null;
  try {
   sessionFactory = HibernateUtil.getSessionFactory();
   session = sessionFactory.getCurrentSession();
   session.beginTransaction();
   Student2 s = new Student2();
   s.setName("小豬");
   Teacher2 t = new Teacher2();
   t.setName("小李");
   TeacherStudent ts=new TeacherStudent();
   ts.setStudent(s);
   ts.setTeacher(t);
   ts.setNote1("以呀呀!!!");
   session.save(s);
   session.save(t);
   session.save(ts);
   session.getTransaction().commit();
  } catch (Exception e) {
   if (session != null) {
    session.getTransaction().rollback();
   }
  }

測試通過!

 

如果自己做測試,可以通過SchemaExport導入表結構

SchemaExport export = new SchemaExport(new AnnotationConfiguration()
    .configure());
  export.create(true, true);


轉自http://blog.sina.com.cn/s/blog_638ea2c50100u47v.html,感謝

記錄學習情況

發佈了30 篇原創文章 · 獲贊 10 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章