The CRUD for Hibernate association relationships

Source: Internet
Author: User

Taking group and user (one-to-many, multi-pair) bidirectional Association as an example, this paper introduces the crud of association relation.

Here are the first two properties

Cascade: Affects only cud in crud, that is, storage (save), update (updated), delete fetch: Affects only r in crud, i.e. read (GET, load)

Cascade (CASCADE): This property only helps us to simplify programming, not the required option if A and B are one-way associations, set the Cascade property in the dominant party if A and B are bidirectional, then both sides set the Cascade property
If there is an association between the two objects, such as user and group many-to-one association if you want to save the user automatically when you save the group, you can set the Cascade (Cascade) property in the @manytoone annotation of the user class in turn, If you want to save the group automatically when you save the user, you can set the CASCADE (Cascade) attribute in the @onetomany annotation of the group class

= (user) session.get (user).  Class, 1), when the multi-party object U is taken out, the corresponding attribute of the object is taken out, which is the default setting of @manytoone. Equivalent to set @manytoone (Fetch=Fetchtype.eager) Conversely, when one object is taken, the multi-party object is not taken out. If you want to take out a multi-party object while taking out the object G, you should set the Fetch property in the @onetomany annotation of the group classto fetch a value of two fetch =  Fetchtype.eager: Executes the statement and takes out fetch=Fetchtype.lazy: The difference between the two when used is similar to the difference between get and load note: For bidirectional correlation, Do not set eager on both sides (there will be redundant query statements issued), you can set the lazy is usually more than a set of eager, one-to-many settings lazy

Group entity classes and user entity classes, and JUnit test classes

@Entity @table (name= "_group") public class group {private int id;private String name;private set<user> users = new have Hset<user> (); @Id @generatedvaluepublic int getId () {return Id;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} @OneToMany (mappedby= "group") public set<user> getusers () {return users;} public void Setusers (set<user> users) {this.users = users;}}

@Entity @table (name= "_user") public class User {private int id;private String name;private Group group;@ id@generatedvaluepublic int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} @ManyToOnepublic Group Getgroup () {return group;} public void Setgroup (group group) {this.group = group;}}

public class Ormappingtest {private static sessionfactory SF = null; @BeforeClasspublic static void Beforeclass () {SF = new Configuration (). Configure (). Buildsessionfactory ();} @AfterClasspublic static void Afterclass () {sf.close ();} @Testpublic void Test () {//below will refine this test () method}}

Let's start the crud practice.

First, add the Cascade property to the @onetomany and @manytoone annotations of the group class and the user class

// Group class @OneToMany (mappedby= "group", cascade={cascadetype.all},fetch=fetchtype.lazy)public set<user> getusers () {    return  users;}

// User Class @ManyToOne (cascade={cascadetype.all}) public Group Getgroup () {     return  Group;}

Then, refine the test () method of the JUnit test class

CRUD----C Add Session.save ()

1. Save the user object while saving the group object automatically

@Testpublic void Test () {Session session = Sf.getcurrentsession (); Session.begintransaction (); Group G = new Group (); G.setname ("Lisi"); User U = new user (); U.setname ("user1"); U.setgroup (g); Session.save (u)   ; Because the Cascade (Cascade) attribute is set in the @manytoone annotation of the user class, only the user object is saved, and the group object is automatically saved Session.gettransaction (). commit ();

2. Save the Group object while automatically saving the user object

@Testpublic void Test () {Session session = Sf.getcurrentsession (); Session.begintransaction (); User U1 = new user (); User U2 = new user (); Group G = new Group (); U1.setname ("user1"); U1.setgroup (g); U2.setname ("user2"); U2.setgroup (g); G.setname ("group1"); G.getusers (). Add (U1), G.getusers (). Add (U2); Session.save (g)   ; Because the Cascade (Cascade) attribute is set in the @onetomany annotation of the group class, only the group object is saved, and the user object is automatically saved Session.gettransaction (). commit ();

CRUD----R session.get () and Session.load ()

1. Remove the Group object while removing the user object

@Testpublic void Test () {Session session = Sf.getcurrentsession (); Session.begintransaction (); User U = (user) Session.get (user.class, 1);   When you remove the multi-party object you will also take out the corresponding property of the object, which is the default setting of @manytoone System.out.println (U.getgroup (). GetName ());   Print output _group The corresponding name value in the table Session.gettransaction (). commit ();}

2. Remove the user object while removing the group object

@Testpublic void Test () {Session session = Sf.getcurrentsession (); Session.begintransaction (); Group G = (group) session.get (Group.class, 2); When you remove a party object G and remove the multiple objects at the same time, you should set the Fetch property for (User u:g.getusers ()) {System.out.println (U.getid () + "," +) in the @onetomany annotation of the group class. U.getname ());  Print out the relevant data in the _user table}session.gettransaction (). commit ();}

CRUD----U Change session.update ()

By removing the user object, you can either change the name of the property in the user object or change the name of the property in the group object that it is cascading with

@Testpublic void Test {Session session = Sf.getcurrentsession (); Session.begintransaction (); User U = (user) Session.get (user.class, 3);   When the multi-party object U is taken out, the corresponding attribute of the object is taken out, which is the default setting of the @manytoone u.setname ("name");                            Change the properties in the User object name U.getgroup (). SetName ("Groupname");            You can also change the property name Session.update (U) in the Group object to which it is cascaded, session.gettransaction (). commit ();}

CRUD----D Delete session.delete ()

Delete a record in the user table

Two different ways, as follows:

 @Testpublic void Testdelete () {Session session = Sf.getcurrentsession (); session.begintransaction ();//   Delete the record with ID value 1 in user table user U = (user) Session.get (user.class, 1);                             When the multi-party object U is taken out, the corresponding attribute of the object is also taken out, which is the default setting of @manytoone u.setgroup (null);                            The correlation relationship should be eliminated before deleting the corresponding record session.delete (U); If you delete it directly, all data related to group and user//delete the record with ID value 2 in the User table Session.createquery ("Delete from user U where u.id=") is deleted because the Cascade property is set. 2 "). Executeupdate (); Session.gettransaction (). commit ();} 

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.