Hibernate多對多之中間表只有兩個外鍵做聯合主鍵

一般情況下,多對多的關聯關係是需要中間表的;

情況一:如果中間表僅僅是做關聯用的,它裏面僅有2個外鍵做聯合主鍵,則使用ManyToMany(不用寫中間表的Model,只需要寫出兩張主表的model即可)

學生表

@Entity
@Table(name = "T_STUDENT")
@SequenceGenerator(name = "SEQ_STUDENT", sequenceName = "SEQ_STUDENT")
public class Student implements Serializable {
 private static final long serialVersionUID = 2524659555729848644L;
 private Long id;
 private String name;
 private Date birthday;
 private int sex;
 private String address;
 private Set<Teacher> teacherList;
 @Id
 @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_STUDENT")
 @Column(name = "ID", nullable = false, precision = 22, scale = 0)
 public Long getId() {
  return id;
 }
 public void setId(Long id) {
  this.id = id;
 }
 @Column(name = "NAME")
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 @Temporal(TemporalType.DATE)
 @Column(name = "BIRTHDAY")
 public Date getBirthday() {
  return birthday;
 }
 public void setBirthday(Date birthday) {
  this.birthday = birthday;
 }
 @Column(name = "sex")
 public int getSex() {
  return sex;
 }
 public void setSex(int sex) {
  this.sex = sex;
 }
 @Column(name = "address")
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
 @ManyToMany(cascade = CascadeType.ALL)
 @JoinTable(name = "T_TEACHER_STUDENT",
   joinColumns = @JoinColumn(name = "student_id"),
   inverseJoinColumns = @JoinColumn(name = "teacher_id"))
 public Set<Teacher> getTeacherList() {
  return teacherList;
 }
 public void setTeacherList(Set<Teacher> teacherList) {
  this.teacherList = teacherList;
 }
}

教師表

@Entity
@Table(name = "T_TEACHER")
@SequenceGenerator(name = "SEQ_TEACHER", sequenceName = "SEQ_TEACHER")
public class Teacher implements Serializable {
 private static final long serialVersionUID = 2297316923535111793L;
 private Long id;
 private String name;
 private int sex;
 private Set<Student> studentList;
 @Id
 @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_TEACHER")
 @Column(name = "ID", nullable = false, precision = 22, scale = 0)
 public Long getId() {
  return id;
 }
 public void setId(Long id) {
  this.id = id;
 }
 @Column(name = "name")
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 @Column(name = "sex")
 public int getSex() {
  return sex;
 }
 public void setSex(int sex) {
  this.sex = sex;
 }
 @ManyToMany(mappedBy = "teacherList", cascade = CascadeType.ALL)
 public Set<Student> getStudentList() {
  return studentList;
 }
 public void setStudentList(Set<Student> studentList) {
  this.studentList = studentList;
 }
}

hibernate.cfg.xml配置2個class類

<mapping class="com.dvn.li.model.Student"/>
<mapping class="com.dvn.li.model.Teacher"/>

測試:

SessionFactory sessionFactory = null;
  Session session = null;
  try {
   sessionFactory = HibernateUtil.getSessionFactory();
   session = sessionFactory.getCurrentSession();
   session.beginTransaction();
   Student s = new Student();
   s.setName("小豬");
   Teacher t = new Teacher();
   t.setName("小李");
   Set<Teacher> t_set = new HashSet<Teacher>();
   t_set.add(t);
   s.setTeacherList(t_set);
   session.save(s);
   
  } catch (Exception e) {
   if (session != null) {
    session.getTransaction().rollback();
   }
  }

 測試通過!!!

很簡單吧!注意HibernateUtil.getSessionFactory()的實現如下:

public class HibernateUtil {
 private static final SessionFactory sessionFactory;

 static {
  try {
   // Create the SessionFactory from hibernate.cfg.xml
   sessionFactory = new AnnotationConfiguration().configure()
     .buildSessionFactory();
  } catch (Throwable ex) {
   // Make sure you log the exception, as it might be swallowed
   System.err.println("Initial SessionFactory creation failed." + ex);
   throw new ExceptionInInitializerError(ex);
  }
 }

 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }
}

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

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


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

記錄學習情況

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