Hibernate: Check if object exists/changed
Posted
by swalkner
on Stack Overflow
See other posts from Stack Overflow
or by swalkner
Published on 2010-01-18T21:40:27Z
Indexed on
2010/05/01
0:37 UTC
Read the original article
Hit count: 312
Assuming I have an object Person with
long id
String firstName
String lastName
String address
Then I'm generating a Person-object somewhere in my application. Now I'd like to check if the person exists in the database (= firstname/lastname-combination is in the database). If not => insert it. If yes, check, if the address is the same. If not => update the address.
Of course, I can do some requests (first, try to load object with firstname/lastname), then (if existing), compare the address. But isn't there a simpler, cleaner approach? If got several different classes and do not like to have so many queries.
I'd like to use annotations as if to say: firstname/lastname => they're the primary key. Check for them if the object exists.
address is the parameter you have to compare if it stayed the same or not.
Does Hibernate/JPA (or another framework) support something like that?
pseude-code:
if (database.containsObject(person)) { //containing according to compound keys
if (database.containsChangedObject(person)) {
database.updateObject(person);
}
} else {
database.insertObject(person);
}
© Stack Overflow or respective owner