"JPA Cascade Save/Cascade deletion" @OneToMany One-to-many (one-way and bidirectional) annotations

Source: Internet
Author: User
Please check the original text
This article will want to introduce you to the JPA cascading save operation.       Before that, I'd like you to take a look at this document and have a general idea of the various attributes of the cascading annotations. In life, there are many relationships that are more than one pair. 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 to a two-way relationship. It is also said that through the student entity, we can get the entity of the school he attends. 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 two-way one-to-many relationship. Generally speaking, 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) PR Ivate Long ID;
A foreign key "SCHOOL_FK" is established 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) Priv Ate Long ID;
@OneToMany (mappedby= "shcool")//settings: Cascading save/new operation. When new schools and students are kept, the newly-built students are also saved @Column (cascade={cascadetype.persist}) private List students;
Manually construct a method for adding students public 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 ("Learn younger 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 cascading save operation.         We set up a cascade save operation on the school entity. We want JPA to do this, when new schools are built, and more students are created.     As long as the student's school is completed and the school is saved, the student who belongs to the school can be saved. }
Cascade Save, test method public void Testpersistcreateschool () {//Cascading save Demo: The Cascade save operation has been added to the school (School) Model: Cascade={cascad          Etype.persist} School School = new School (); School.setname ("school");
Student st1 = new Student ();          St1.setname ("Learn younger brother");          St1.setschool (school);                   No need to show save student St1//studnetdao.save (ST1);          Student st2 = new Student ();          St2.setname ("seniors");          St2.setschool (school); No need to show save student St2//studnetdao.save (ST2);
Add Student school.addstudent (ST1);          School.addstudent (ST2); Schooldao.save (school)/Save school, new students in the school also [St1, St2] was saved. (Cascading Save)}
    //Test Delete     public void Testdeleteschool () {     The first step in the         //Revolution is to create a school.             testcreate ();             schooldao.delete (school)//Background error              //avax.persistence.rollbackexception:error While commiting the transaction caused by:        //java.sql.batchupdateexception:cannot delet E or update a parent row:a FOREIGN KEY constraint ...                              //We've known before, To remove the maintained side of a relationship, you must first disassociate the relationship from the maintenance side. To remove it normally. So what we have to do is, first from the student side, the dissolution of the relationship.              List<Strudnet> students = School.getstUdentlist ();         for (int i=0;i<students.size (); i++) {                 student stu = Students.get (i);                 stu.setschool ( (null);/manually disassociate        &nbsp from student entity;          schooldao.delete (school); Now, the school is normally deleted. Information on the school's two students is still kept in the database. It's just that they don't have a school.
        //See here, you will surely reproach me. JPA is not very powerful. Not very flexible and changeable. Isn't it amazing?         //Why delete an entity, but also need to recycle the relationship, so cumbersome operation.         //In fact, we have a way to delete schools directly. Also, there is no need for such a loop to disassociate from the student entity. But, believe me, this method you may not accept. Next, let's look at the JPA cascading deletions.         //Revise school model, students field () Note: @Column (Cascade={cascadetype.persist} )         //to read: @Column (Cascade={cascadetype.persist,cascadetype.remove} To add a cascading delete operation. So now you can just call the way to delete the school.         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         //printing is: null    Yes, you're right. All the students in the school were also deleted by the cascade ...         //at this point, you should understand the cascade deletion of JPA. The object that it deletes is an entity. Cascade refers to a cascading entity. If a cascade deletion is added to the student model, delete a student, and the school that the student belongs to will be deleted.。         //So, here, I want to remind you. The cascade delete operation should be used with caution. Because, he's too destructive. Cascading deletes are not for a field, but for the entity it manages. }         &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&AMP;NB

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.