Understanding Hibernate saveOrUpdate and the Persistence Life Cycle
- by Stephano
The books that I've read regarding hibernate are, at best, reference tomes. They very seldom have good code examples, so I tend to use online resources for those needs.
However, I've always had a problem understanding the basic idea of hibernate persistence. I've read the books and understand the concepts, but in practice, I often see results that I don't understand. Perhaps you all can help, as you have in the past.
Let's look at a simple example of a dog and a cat that are friends. This isn't a rare occurrence. It also has the benefit of being much more interesting than my business case.
We want a function called "saveFriends" that takes a dog name and a cat name. We'll save the Dog and then the Cat. For this example to work, the cat is going to have a reference back to the dog. I understand this isn't an ideal example, but it's cute 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, assume for a minute that I would like to use either example A or example B to save my friend. Is one better than the other to use?
I'll understand if neither of those examples work, but please explain why.