Understanding Hibernate saveOrUpdate and Life Cycle Lifecycle

Look at a simple example of a dog and cat who are friends. This is not a rare occurrence. It also has the advantage of being much more interesting than my business.

We need a function called "saveFriends" that takes the name of the dog and the name of the cat. We will save the Dog, and then the Cat. For this example to work, the cat will have a link to the dog. I understand that this is not a perfect example, but it is nice and works for our purposes.

FriendService.java

public int saveFriends(String dogName, String catName) {
    Dog fido = new Dog();
    Cat felix = new Cat();

    fido.name = dogName;
    fido = animalDao.saveDog(fido);

    felix.name = catName;
    [ex.A]felix.friend = fido;
    [ex.B]felix.friend = animalDao.getDogByName(dogName);
    animalDao.saveCat(felix);
}

AnimalDao.java (extends HibernateDaoSupport)

public Dog saveDog(Dog dog) {
    getHibernateTemplate().saveOrUpdate(dog);
    return dog
}

public Cat saveCat(Cat cat) {
    getHibernateTemplate().saveOrUpdate(cat);
    return cat;
}

public Dog getDogByName(String name) {
    return (Dog) getHibernateTemplate().find("from Dog where name=?", name).get(0);
}

Now suppose I would like to use either example A or example B to save my friend. Is it better to use another?

, B "null-null null "? , , , .

, , , .

+3
3

, A, B, . ?

( B, Hibernate , ) ( B), . .

, B "null-null null "?

(. ). B . .

, , , .

() id, .

+4

hibernate

saveOrUpdate() :

,

, , ,

, save() it

, , save() it

a , version - , , save() it

()

, , fido, , .

+2

, . B, , , - , , , .

Communication with db usually suffers with a rather high delay, so batch processing is used to send several changes at once, which reduces the delay for each statement. Breaking the set of changes into many small changes leads to relatively higher overhead costs per operator than a large group of changes. Therefore, it is best to present the changes together when possible.

+2
source

Source: https://habr.com/ru/post/1750181/


All Articles