Hibernate configuration Bidirectional Multi-join (not complete & #183; & #183; & #183; & #183; & #183; & #183; & #183 ;), hibernate to be continued

Source: Internet
Author: User

Hibernate is configured with two-way multi-Association (To be continued...), and hibernate is not to be continued.

How many times does it take to practice from unfamiliar to skilled? You can only find this answer for yourself.

Taking Student and Course as examples, a Student can select multiple courses, and a Course can also be selected by multiple students;

First, create a persistent class Student.

1 package bean; 2 3 import java. util. set; 4 5 public class Student {6 private long id; 7 private String name; // Student name 8 private Set <Course> courses; // The course 9 selected by the student // the set and get Methods 10 are omitted}

The next step is the persistence Course class.

1 package bean; 2 3 import java. util. set; 4 5 public class Course {6 private long id; 7 private String name; // Course name 8 private Set <Student> students; // select 9 students for the course // omit set and get Method 10}

Then the object link ing file Student. hbm. xml:

 1 

The implementation of multiple-to-multiple associations requires a connection table. the attribute of <set> indicates the name of the connection table, and <key> indicates the field name of the connection table referring to the foreign key of the students table id; the class in <strong-to-sequence> specifies the many-to-many association classes with Student, and the column specifies the connection table to refer to the Course ing table (Here we use Course. hbm. xml ing to the courses table) the field name of the foreign key of the id, Course. hbm. <set> Configuration and Student. hbm. <set> inverse in xml:

Course. hbm. xml:

 

 1 

 

Note: The name of the connection table set in the two ing files and the names of the two fields in the connection table must be the same, for example, the connection table names are "students_courses" and "student_id ", otherwise, it may cause unnecessary trouble; the primary key of the connection table is the joint primary key (student_id, course_id ).

The structures and Mappings of the three tables are as follows:

Next, save the object:

 

 1 Student s1=new Student();   2 s1.setName("lisi");   3 Course c1=new Course();   4 c1.setName("English");   5 Course c2=new Course();   6 c2.setName("science");   7 s1.setCourses(new HashSet<Course>());   8 c1.setStudents(new HashSet<Student>());   9 c2.setStudents(new HashSet<Student>());  10 s1.getCourses().add(c1);  11 s1.getCourses().add(c2);  12 c1.getStudents().add(s1);  13 c2.getStudents().add(s1);  14   15 session.save(c1);  16 session.save(s1);

 

(1) If both inverse values of the two ing files are set to false (default), an exception (repeated primary keys) will occur, leading to insertion failure:

Org. hibernate. exception. ConstraintViolationException: cocould not execute JDBC batch update

Caused by: java. SQL. BatchUpdateException: Duplicate entry '1-1' for key 'primary'

Com. mysql. jdbc. exceptions. jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1-1' for key 'primary'

Explanation: If the inverse values in the two ing files are true, Student and Course both maintain the association, that is, inserting records into the connection table at the same time will lead to duplicate primary keys and insertion failure.

Solution:

-- Set inverse of one party to true to maintain the association between the other party;

-- Set s1.getCourses (). add (c1); or c1.getStudents (). add (s1); Delete, because if the students set in a Course is empty, it will not add records to the connection table, the primary key will not conflict with the insert record of Student to the connection table.

(2) If both of them are set to true, the SQL statement that is executed only to insert records to the two tables (both of them think that the other table will maintain the association relationship) is:

 

 

1 Hibernate: insert into courses (name, id) values (?, ?)  2 Hibernate: insert into students (name, id) values (?, ?)  3 Hibernate: insert into courses (name, id) values (?, ?) 

(3) If the inverse of one party is set to true, the SQL statement output when data is inserted normally is:

1 Hibernate: insert into courses (name, id) values (?, ?)  2 Hibernate: insert into students (name, id) values (?, ?)  3 Hibernate: insert into courses (name, id) values (?, ?)  4 Hibernate: insert into students_courses (student_id, course_id) values (?, ?)  5 Hibernate: insert into students_courses (student_id, course_id) values (?, ?)  

Delete Student records:

 

1 Student s=(Student)session.get(Student.class, 2L);  2 session.delete(s);

 

Note:

(1) If it is not Student, maintain the association:

-- If the connection table students_courses contains a record that references this record in the students table (that is, the student_id is 2L in the students_courses table), the deletion fails.

-- If the connection table students_courses does not reference the record in the students table, the record can be deleted successfully.

(2) If Student is used to maintain the association:

-- First Delete the record of this record in the connection table students_courses with reference to the students table, and then delete the student record from the students table


Query all courses selected by a student:

 

1 Student s=(Student)session.get(Student.class, 2L);  2           Set<Course> set=s.getCourses();  3             4           for (Iterator iterator = set.iterator(); iterator.hasNext();) {  5 Course course = (Course) iterator.next();  6 System.out.println(course.getName());  

 

A student chooses a new course (adds a record in the join table ):

1 Student s=(Student)session.get(Student.class, 2L);  2 Course c=(Course)session.get(Course.class,1L );  3 s.getCourses().add(c);  4 c.getStudents().add(s);

Delete A Course Selection Record of a student (delete a record in the connection table ):

 

1  Student s=(Student)session.get(Student.class, 2L);  2 Course c=(Course)session.get(Course.class,1L );  3 s.getCourses().remove(c);  

 

(At this time, only one record in the connection table will be deleted, and the record in the Students and courses tables will not be modified)

Note: bidirectional multiple-to-multiple splitting can also be divided into two multiple-to-one
1  <many-to-one name="stu" class="Student">2           <column name="stuId"></column>3         </many-to-one>4         <many-to-one name="cou" class="Course">5           <column name="couid"></column>6         </many-to-one>

 

 

When you encounter difficulties or problems, you can solve them only if you do not understand them.

Thank you for guiding me: http://www.cnblogs.com/smbk/

 

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.