"JPA Cascade save/cascade delete" @OneToMany (bidirectional) one-to-many "turn"

Source: Internet
Author: User

"http://blog.sina.com.cn/s/blog_625d79410101dbdd.html"

read the top two help documents "jpa" @OneToOne one-way and "jpa" @OneToOne two-way presumably everyone is already full of curiosity and anticipation for cascading operations. Then this article will introduce you to the JPA Cascade save Operation. Before that, I would like you to look at this document and have a general understanding of the various properties of the cascading annotations. Portal: explanation of "JPA" cascading tags @Cascadein life, There are many relationships that are one-to-many. The relationship between School (school) and Studnet (student) is a typical one-to-many relationship. There are many students in a School. But a student can only belong to a School. here, we set this relationship as a two-way relationship. It is also said that through the student entity, we can get the entity of the school he Attended. similarly, through a school entity, we can also get a collection of student entities that are enrolled in this School.  --------< Examples >---------------------------------------------------------------------------------------- ------------------ //student model, The maintenance side of this bidirectional one-to-many relationship. In general, in a two-way one-to-many relationship, the "many" end, is generally the maintenance side of the Relationship. @Entity@Table (name = "student")public class Student {@Id@GeneratedValue (strategy = generationtype.auto)Private Long id; //establish foreign key "school_fk" in the table    @ManyToOne@JoinColumn (name= "school_fk")Private School School;   //omit several get/set}  @Entity@Table (name = "school")public class School {@Id@GeneratedValue (strategy = generationtype.auto)Private Long id; @OneToMany (mappedby= "shcool")//settings: Cascade save/new Operation. When new schools and students are created, the newly created students are saved as Well.@Column (cascade={cascadetype.persist})Private List students; //manually construct methods to add studentspublic void Addstudent (strudent Stu) {if (stu! = null) {Students.add (stu);            }    } //omit several get/set}-----------------------------------------------------< test Methods >----------------------------------------- ---------------------public class Test () { public void Testcreate () {School School = new School ();school.setname ("school"); Student st1 = new Student ();st1.setname ("learning brother");St1.setschool (school);Studnetdao.save (st1);       Student st2 = new Student ();st2.setname ("seniors");St2.setschool (school);Studnetdao.save (st2); //add Student school.addstudent (st1);school.addstudent (st2); Schooldao.save (school);//the Save method above is not a cascade save Operation. We set up a cascade save operation on the school Entity. //we want JPA to do so when new students are newly created. Once the Student's school has been set up, the school can be saved and the students who belong to the school will be Saved.     } //cascade save, test methodpublic void Testpersistcreateschool () {            //cascade Save demo: A cascade save operation has been added to the school (School) Model:cascade={cascadetype.persist}       School School = new School ();school.setname ("school"); Student st1 = new Student ();st1.setname ("learning brother");St1.setschool (school); // do not need to display save student St1 //studnetdao.save (st1);       Student st2 = new Student ();st2.setname ("seniors");St2.setschool (school);//do not need to display save student st2 //studnetdao.save (st2);  //add Student school.addstudent (st1);school.addstudent (st2); Schooldao.save (school);//save The school, the new students in the school also [st1, st2] was Saved. (cascade Save)    } //test Deletepublic void Testdeleteschool () {The first step of the revolution is to create Schools.testcreate ();Schooldao.delete (school);//background Error//avax.persistence.rollbackexception:error while commiting the transaction caused By:java.sql.BatchUpdat Eexception:cannot Delete or update a parent row:a FOREIGN KEY constraint ...              we already know that to remove the maintained side of a relationship, you must first release the relationship from the maintenance Side. To delete normally. So what we have to do is to get the relationship out of the Student's side First. list<strudnet> students = School.getstudentlist (); For (int i=0;i<students.size (); i++) {Student stu = Students.get (i);Stu.setschool (null);//manually Remove the system from the student entity}Schooldao.delete (school);//the School is now normally deleted. The School's two student information is still stored in the Database. It's just that they don't have a school.  ///see here, You will certainly blame Me. Isn't JPA very powerful? Not very flexible? Isn't it amazing? //why Delete an entity, also need to recycle the relationship, so cumbersome operation?! //actually, We have the means to delete the school directly. also, There is no need to perform this loop from the student entity to remove the relationship from the Operation. but, believe me, you may not accept this Approach. below, Let's look at the cascade deletions for Jpa. //modify The School's model, the student field () comment:@Column (cascade={cascadetype.persist})///change to: @Column (cascade={cascadetype.persist,cascadetype.remove}) to add a cascade delete Operation. well, Now you can call the method of deleting the school directly. Schooldao.delete (school);//now, The school has been deleted normally. but, the next scene, you may not want to see. stduent stu = studentdao.findbyname (seniors ");The result of the printing is: null yes, you read it right. All the students in the school were also deleted ...//at this point, you should be aware of the JPA Cascade Deletions. The object it deletes is an Entity. Cascading refers to cascading entities.        if, in the Student's model, a cascade delete operation is added, Deleting a student will delete the Student's School. so, here, I want to remind You. The cascade delete operation should be used with Caution. because, His destructive is too big. The Cascade delete operation is not for a field, but for the entity it Manages.}       //test Deletepublic void testdeletestudent () { Create schools and studentstestcreate ();Studentdao.delete (st1);//at This time, st1 (the student named "learning brother" at the time of Creation) has been removed from the Database. But the school he belongs to is not Affected. however, St1 has been removed from the School's student Collection.         This is all done by Jpa. now, Let's assume: we didn't do that. St1 was not deleted. The school still has two Students.//in The stuent model, add a cascade delete Operation. @JoinColumn (name= "school_fk", Cascade={cascadetype.remove}) and the Cascade delete operation is also added to the school model. At this point, the database has only one school and two students of Information.Studentdao.delete (st1);wow, the whole world is Clean. If you look at the database at this Time. You will find that all the data is Gone.        Why is that? Let's see what JPA has done: 1: delete st1 2:school is st1 cascade delete 3:st2 be school cascade delete//so, you will find that all the information in the database Disappears. of course, If there were other schools and other schools in the Database. Then their message is Unaffected.//i'm sorry to have done so Much. I just want to remind you that you must be careful to use this cascade delete Operation. Do not add a cascade save delete operation when creating the Model. Must be according to their own needs. and the actual effect of the operation, after careful deliberation, then put into Action. otherwise, you come straight to a cascadetype.all. most of the cases, it brings you painful memories. }//omit Main Method}

JPA Cascade save/cascade Delete @OneToMany (bidirectional) one-to-many "turn"

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.