Hibernate multi-to-many removal problem resolution

Source: Internet
Author: User
Tags uuid

Original source: http://superleo.iteye.com/blog/154587

Hibernate Many of the examples of many, but a closer look, most are saved, delete talk less, but there are a lot of problems, so there must be a simple test, the following we have a simple many-to-many relationship between the establishment of teacher teacher and curriculum course is a many-to-many relationship, Pojo and XML are configured as follows. Pojojava Code Collection Code/*** Course Entity * See Table:tbl_course*/   PackageCom.leo.domain; ImportJava.util.HashSet; ImportJava.util.Set; /**  * @authorSuperleo **/   Public classCourse {PrivateString ID; PrivateString name; Privateset<teacher> teachers =NewHashset<teacher>();  PublicString getId () {returnID; }         Public voidsetId (String id) { This. ID =ID; }         PublicString GetName () {returnname; }         Public voidsetName (String name) { This. Name =name; }         PublicSet<teacher>getteachers () {returnteachers; }         Public voidSetteachers (set<teacher>teachers) {           This. Teachers =teachers; }} Java code Collection code/*** Teacher Entity * See Table:tbl_teacher*/   PackageCom.leo.domain; ImportJava.util.HashSet; ImportJava.util.Set; /**  * @authorSuperleo **/   Public classTeacher {PrivateString ID; PrivateString name; Privateset<course> courses =NewHashset<course>();  PublicString getId () {returnID; }         Public voidsetId (String id) { This. ID =ID; }         PublicString GetName () {returnname; }         Public voidsetName (String name) { This. Name =name; }         PublicSet<course>getcourses () {returncourses; }         Public voidSetcourses (set<course>courses) {           This. courses =courses; The configuration file is also very simple: The XML code Collection code<?xml version= "1.0"?> <! DOCTYPE hibernate-Mapping Public"-//hibernate/hibernate Mapping DTD 3.0//en" "Http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > className= "Com.leo.domain.Course" table= "Tbl_course"Batch-size= "dynamic-insert=" true "dynamic-update=" true "> <id name=" id "column=" id "> <gen Eratorclass= "uuid"/> </id> <property name= "name" column= "name" type= "string"/> <set Access= "Property" lazy= "true" inverse= "false"Cascade= "Save-update" name= "Teachers" batch-size= "ten" fetch= "select"Table= "Tbl_teacher_course" > <key column= "fk_course_id"/> <many-to-manyclass= "Com.leo.domain.Teacher"column= "fk_teacher_id"/> </set> </class> XML code Collection code<?xml version= "1.0"?> <! DOCTYPE hibernate-Mapping Public"-//hibernate/hibernate Mapping DTD 3.0//en" "Http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > className= "Com.leo.domain.Teacher" table= "Tbl_teacher"Batch-size= "dynamic-insert=" true "dynamic-update=" true "> <id name=" id "column=" id "> <gen Eratorclass= "uuid"/> </id> <property name= "name" column= "name" type= "string"/> <set Access= "Property" lazy= "true" inverse= "true"Cascade= "Save-update" name= "courses" batch-size= "Ten" fetch= "select"Table= "Tbl_teacher_course" > <key column= "fk_teacher_id"/> <many-to-manyclass= "Com.leo.domain.Course"column= "fk_course_id"/> </set> </class> first insert some records into the database: Java Code Collection Code Public voidTestsave () {Session session=hibernatesessionfactory.getsession ();            Session.begintransaction (); //Create CourseCourse C1 =NewCourse (); Course C2=NewCourse (); C1.setname (C); C2.setname ("Java"); //Create teacherTeacher T1 =NewTeacher (); Teacher T2=NewTeacher (); T1.setname ("Leo"); T2.setname ("Rose"); //Create Relationshipc1.getteachers (). Add (T1);          C1.getteachers (). Add (T2);          T1.getcourses (). Add (C1);            T2.getcourses (). Add (C1); /*because the main control cascade is set to Save-update, if set to none, the code below will need to be turned on, otherwise the error*/          //session.save (t1); //Session.save (T2); Session.save (C1);          Session.gettransaction (). commit ();      Session.close (); The following are some of the results of the test:1If the cascade is set to all by the main control or the prosecution, delete is related to delete cascade deletion, and the records of both ends and the intermediate table are deleted, which is usually very rare, so if you want to do this, simply set it to all, Delete makes it easy to delete the relationship and the records at both ends. 2you only want to delete the records at one end and the associated information for the intermediate tables. This requirement is usually very common. At this time, the Cascade setting is any cascading constraint related to delete. Here's how to delete: If you delete the master, you simply delete the record, the Cascade relationship and the master's record are deleted, but the prosecution's record still exists. Therefore, it is the simplest and most straightforward to delete many-to-many from the main control side. The code is as follows: Java Code Collection Code/*** Many-to-many master delete (can delete intermediate table records)*/       Public voidTestdelete () {String ID= "402881ee175f04be01175f04c05d0001"; Session Session=hibernatesessionfactory.getsession ();          Session.begintransaction (); Course C1= (Course) session.get (Course.class, id);          Session.delete (C1);          Session.gettransaction (). commit ();      Session.close (); If you want to delete the accused at this time, then I regret to tell you that you only do half, you just simple to the prosecution's record deleted, the relationship still exists in the middle table, the system at any time because of your associated access error, the code is as follows: Java Code Collection Code/*** Many-to-many controlled parties deleted (Unable to delete intermediate table records)*/   Public voidTestdeletebyinverse () {String ID= "402881ee175a2e7c01175a2e7ead0003"; Session Session=hibernatesessionfactory.getsession ();      Session.begintransaction (); Teacher T1= (Teacher) session.get (Teacher.class, id);      Session.delete (t1);      Session.gettransaction (). commit ();  Session.close (); If you want to delete the accused, double want to delete the association, see the following code: Java Code Collection Code/*** Many-to-many controlled parties Delete (can delete intermediate table records)*/   Public voidTestDeleteByInverse2 () {String ID= "402881ee175f04be01175f04c06c0002"; Session Session=hibernatesessionfactory.getsession ();        Session.begintransaction (); Teacher T1= (Teacher) session.get (Teacher.class, id); Set<Course> cs =t1.getcourses ();  for(Course c:cs) {c.getteachers (). Remove (T1);      } session.delete (t1);      Session.gettransaction (). commit ();  Session.close (); }  

Hibernate multi-to-many removal problem resolution

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.