Hibernate multi-to-Multi-intermediate tables are implemented by annotation of other fields, and hibernate multi-to-many

Source: Internet
Author: User

Hibernate multi-to-Multi-intermediate tables are implemented by annotation of other fields, and hibernate multi-to-many

Requirements:

Two entity classes: The Teacher. class Student. class intermediate table contains an additional field: score


Teacher. calss

Id Name
1 Mr. zhang
2 Mr. wang

Student. class

Id Name
1 Xiaoming
2 Xiaohong

Intermediate table

Id Teacher_id Student_id Score
1 1 1 89
2 1 2 90

Solution:

According to the traditional multi-to-Multi-annotation implementation, the intermediate table uses its own id as the default primary key, and contains two entity classes IDs. There are three fields in total and no additional fields can be added.

The solution is to split ManyToMany into two onetoworkflow instances.


Solution Process:

Show the view of this blog: The http://blog.csdn.net/liuxianbing119/article/details/7283769 knows how to deal with this, but can be added successfully, the deletion has not been successful.

Later I turned to the introduction in the wiki: http://en.wikibooks.org/wiki/Java_Persistence/ManyToMany

I knew this method was correct. I tried it several times and finally succeeded.


Code:

1. AbstractEntity. java

package com.cc.persistence;import java.io.Serializable;public abstract class AbstractEntity implements Persistable {public abstract Serializable getInternalId();@Overridepublic boolean equals(Object o) {if (o == null) return false;if (!o.getClass().getName().equals(this.getClass().getName())) return false;return ((Persistable)o).getInternalId().equals(this.getInternalId());}@Overridepublic int hashCode() {return this.getInternalId().hashCode();}}

2. Teacher. java

package com.xx;import java.io.Serializable;import java.util.Date;import java.util.Set;import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.FetchType;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.OneToMany;import javax.persistence.OrderBy;import javax.persistence.SequenceGenerator;import javax.persistence.Table;import javax.persistence.Transient;@Entity@Table(name = "teacher")public class Teacher extends AbstractEntity{/** *  */private static final long serialVersionUID = 2392788383432498751L;private Long id;private String name;private Set<TeacherStudent> teacherStudents;@Id@GeneratedValue(strategy = GenerationType.AUTO)public Long getId() {return id;}public void setId(Long id) {this.id = id;}@Column(name = "name", length = 256)public String getName() {return name;}public void setName(String name) {this.name = name;}@OneToMany(mappedBy = "teacher")public Set<NoticeGroup> getTeacherStudents() {return teacherStudents;}public void setTeacherStudents(Set<TeacherStudent> teacherStudents) {this.teacherStudents = teacherStudents;}@Override@Transientpublic Serializable getInternalId() {return id;}}

3. Student. java

package com.xx;import java.io.Serializable;import java.util.Date;import java.util.HashSet;import java.util.Set;import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.FetchType;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.OneToMany;import javax.persistence.OrderBy;import javax.persistence.SequenceGenerator;import javax.persistence.Table;import javax.persistence.Transient;@Entity@Table(name = "student")public class Student extends AbstractEntity {/** *  */private static final long serialVersionUID = 6380182108640048430L;private Long id;private String name;private Set<TeacherStudent> teacherStudents;@Id@GeneratedValue(strategy = GenerationType.AUTO)public Long getId() {return id;}public void setId(Long id) {this.id = id;}@Column(length = 256)public String getName() {return name;}public void setName(String name) {this.name = name;}@OneToMany(mappedBy = "student")public Set<TeacherStudent> TeacherStudents() {return teacherStudents;}public void setTeacherStudents(Set<TeacherStudent> teacherStudents) {this.teacherStudents = teacherStudents;}@Override@Transientpublic Serializable getInternalId() {return id;}}

4. TeacherStudent. java

package com.xx;import java.io.Serializable;import java.util.Date;import java.util.HashSet;import java.util.Set;import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.FetchType;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.ManyToOne;import javax.persistence.Table;import javax.persistence.Transient;@Entity@Table(name = "teacher_student")public class TeacherStudent extends AbstractEntity {/** *  */private static final long serialVersionUID = 4876371202187846251L;private Long id;private Teacher teacher;private Student student;private Integer score; @Id@Column(name = "id", nullable = false)@GeneratedValue(strategy = GenerationType.AUTO)public Long getId() {return id;}public void setId(Long id) {this.id = id;}@ManyToOne@JoinColumn(name = "teacher_id")public Teacher getTeacher() {return teacher;}public void setTeacher(Teacher teacher) {this.teacher = teacher;}@ManyToOne@JoinColumn(name = "student_id")public Student getStudent() {return student;}public void setStudent(Student student) {this.student = student;}@Column(name="score")public Integer getScore() {return score;}public void setScore(Integer score) {this.score = score;}@Override@Transientpublic Serializable getInternalId() {// TODO Auto-generated method stubreturn id;}}

5. TeacherDaoImpl. java

Add a teacher-student relationship:

@Overridepublic boolean addStudentScore(Long teacherId,Long studentId,Integer score) {// TODO Auto-generated method stubStudent student = (Student) studentDao.findById(studentId);Session session = this.getSession();Transaction tx = null;try {tx = session.beginTransaction();Teacher teacher = (Teacher) session.get(getEntityClass(), teacherId);if (teacher != null && student != null) {//new TeacherStudentTeacherStudent ts = new TeacherStudent();ts.setTeacher(teacher);ts.setStudent(student);ts.setScore(score);session.save(ts);session.flush();tx.commit();return true;}} catch (Exception e) {if (tx != null)tx.rollback();} finally {session.close();}return false;}

Delete a teacher-student relationship:

@Overridepublic boolean removeStudentScore(Long teacherId,Long studentId) {// TODO Auto-generated method stubStudent student = (Student) studentDao.findById(studentId);Session session = this.getSession();Transaction tx = null;try {tx = session.beginTransaction();Teacher teacher = (Teacher) session.get(getEntityClass(), teacherId);Set<TeacherStudent> teacherStudents = null;if (teacher != null && student != null) {teacherStudents = teacher.getTeacherStudents();if (teacherStudents.size()>0){for(TeacherStudent teacherStudent:teacherStudents){if(teacherStudent.getStudent().getId().equals(studentId) && teacherStudent.getTeacher().getId().equals(teacherId)){session.delete(teacherStudent);}}}session.flush();tx.commit();return true;}} catch (Exception e) {if (tx != null)tx.rollback();} finally {session.close();}return false;}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.