Hibernate (10) Crud for association relationships

Source: Internet
Author: User

First, save

1.

Suppose a group has more than one user, a user belongs to only one group, and when the user object is saved to the database, you can

New User (); U.setname ("U1"new  Group (); G.setname ("G1"=  Sessionfactory.getcurrentsession (); S.begintransaction (); S.save (g); // default hibernate does not help us save s.save (U); s.gettransaction (). commit ();

It is important to note that Hibernate does not save the group object for us by default and should be set.

@ManyToOne has an attribute cascade (CASCADE), Cascadetype it has

(1) All: objects that are cascaded to the current object are all manipulated by hibernate

(2) Merge: Cascade (Merge=save+update) when calling the merge () method (when merging)

(3) PERSIST: When the PERSIST () method is called (stored in the case) cascade

(4) Pefresh: When a session load an object and its cascade object into memory from the database, and another session modifies the object in the database, hibernate refreshes the object for the first Sesson load Object Cascade ( A you need to read the data after B has changed)

(5) Remove: Cascade in case of deletion

(The Cascade property indicates what action to make when the associated object is bound together.)

Test: Modify the @manytoone annotation on the Getgroup () method of the user class to @manytoone (Cascade= (Cascadetype.all)), and then comment out S.save (g) in the code block above, Run the program to discover that the group will be automatically saved to the database by hibernate.

2.

We save the user, the associated group hibernate will help us to deposit, if we save group, the associated user will help us to save it? Answer: No

New user (); U1.setname ("U1"new  User (); U1.setname ("U2"new  User (); U1.setname ("U3"new  Group (); G.setname ("G1"=  Sessionfactory.getcurrentsession (); S.begintransaction (); S.save (g); // if not set here, U1,U2,U3 will not automatically help us to save S.gettransaction.commit ();

If you want hibernate to help us deposit the group's associated object, you need to set it up: Modify the annotation @onetomany (mappedby= "group") on the Getusers () method in the group class to @onetomany (Mappedby = "Group", Cascade= (Cascadetype.all)), note: If this is only set, U1,U2,U3 group_id is null after the database is saved, because the Group property in the U1,u2,u3 object is null, So you need to add u1.setgroup (g) to the code block, U2.setgroup (g), U3.setgroup (g).

Law: (1) Many-to-one relationship is simpler to operate from many parties, and (2) If the association relationship is bidirectional, it is necessary to set up navigation (Mappedby) and (3) bidirectional relationship to set bidirectional association in the program.

Second, read

1. Get mode

Let's get a user out of the database first.

Session s = sessionfactory.getcurrentsession (); S.begintransaction (); // when we take this object out of the database, the associated group object will be taken out regardless of whether the cascade is set . User U = (user) s.get (user).  Class , 1); S.gettransaction (). commit;

We get a group out of the database, regardless of the set cascade does not take the associated user out, cascade only in the time of storage, read need to set up another:

Modify the annotation @onetomany (mappedby= "group", Cascade= (Cascadetype.all)) on the Getusers () method in the group class to: @OneToMany (mappedby= "group", Cascade= (Cascadetype.all), Fetch=fetchtype.eager), and then you can write in the code block:

Group G = (group) s.get (group).  Class, 1); // If you do not add a fetch, the associated user is not taken out  for (User u:g.getusers ()) {    System.out.println (U.getname ());  }

The Getgroup () method on the user class is annotated @manytoone the default fetchtype is eager, because

When we take this user object out of the database, the associated group object will be removed regardless of whether the cascade is set.

When we add an attribute fetch=fetchtype.lazy to the annotation @manytoone in the user class, it is only taken when we use the group of the User association:

Session s == (user) s.get (user).  Class , 1); // This will not remove group System.out.println (U.getgroup (). GetName ()); // This will remove the group s.gettransaction (). commit; // System.out.println (U.getgroup (). GetName ()); This will result in an error no session, because the session has been closed. If set to eager, no error is provided. 

Fetchtype is an enumeration type that has:

(1) EAGER: (craving) Define that data must be eagerly fetched

(2) Lazy: (lazy) Define that the data can be lazily fetched

2. Load mode

Third, update

Session s == (user) s.load (user).  Class , 1); U.setname ("user"); U.getgroup (). SetName ("G"); S.gettransaction (). commit (); // will issue two update statements

This can be done but we usually update the object in a free state, and when the user is in a free state, the session is closed and cannot be saved.

Session s == (user) s.get (user).  Class, 1); S.gettransaction (). commit (); U.setname ("user"); U.getgroup (). SetName ("group"  = sessionfactory.getcurrentsession (); S2.begintransaction (); s2.update (u) ; // When the Getgroup () method annotation in the user class @manytoone add a property Cascade=cascadetype.all, the group is updated, or the Update method does not update the group when it is executed S2.gettransaction (). commit ();

Iv. deletion

1. Delete a user

Session s == (user) s.load (user).  Class, 1); S.delete (u) ; // at this point you will be removed and then all user associated with the group object of the U Association will be deleted s.gettransaction (). commit ();

If you do not want to delete the group:

U.setgroup (null); S.delete (u);

You can also use HQL:

Session s = sessionfactory.getcurrentsession (); S.begintransaction (); S.createquery ("Delete from User u where U.id=1 "); S.gettransaction (). commit ();

2. Delete Group

Session s == (group) s.load (group).  Class, 1); S.delete (g); // The G-Delete will delete all the user associated with the G object (Cascade=all, of course)s.gettransaction (). commit ();

If you do not want to delete all user, you can set the user's group_id to null.

Hibernate (10) Crud for association relationships

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.