简体   繁体   中英

Hibernate optimization when saving multiple many-to-one relationships

I am currently working with tables with multiple many-to-one relationships and I'm trying to implement all of them using Hibernate.

For example, three tables I have are:

Product(id, pname), Users(id, pid, gid, uname), Group(id, gname)

Group is in an one-to-many relationship with Users

Product is also in an one-to-many relationship with Users

Users is in a many-to-one relationship with both Product and Group.

A sample of data I would receive is below:

Line 0: pname   uname   gname
Line 1: Razer   Billy   admin
Line 2: Razer   Sally   admin
Line 3: Razer   Benji   admin
Line 4: Yahoo   Molly   admin
...

My correct flawed loop for the data goes like this:

// Three lists of same size created, 
// each list is a column of the sample data from above
// ...

for(int i = 0; i < plist.size; i++){
     Product ptemp = new Product(plist.get(i));
     Group gtemp = new Group(glist.get(i));
     Users utemp = new Users(ptemp, gtemp, ulist.get(i));

     Set<Users> users = new HashSet<Users>();
     users.add(utemp);

     ptemp.setUsers(users);
     gtemp.setUsers(users);

     session.save(ptemp);
     session.save(gtemp);
}

Playing around with hibernate, I have also noticed that when I change my for loop to

for(int i = 0; i < plist.size; i++){
     Product ptemp = new Product(plist.get(i));
     Group gtemp = new Group(glist.get(i));
     Users utemp = new Users(ptemp, gtemp, ulist.get(i));

     session.save(ptemp);
     session.save(gtemp);
     session.save(utemp);
}

The results on the database are the same as before.

Is the second way a better way in hibernate? Or is the practice of storing a dependent entity directly to database something unacceptable in hibernate?

Thanks a lot for your help!

If I understand correctly what you are asking is in what order should the related objects be persisted when it comes to parent/child relationship in Hibernate?

What you have is a Group object that has a collection of User objects in a bidirectional relationship and a Product object that is related to a collection of User objects also bidirectionally. How to manage these types of relationships is documented below:

http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#example-parentchild

Hibernate recommends to manage the state of the relationship meaning the link from child to parent object from the state of the child object.

The first and second approach may work but they may result in different number of sql statements issued to insert the individual objects. It all depends on how you map the relationships.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM