views:

431

answers:

1

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);
}
+1  A: 

I'd like to use annotations as if to say: firstname/lastname => they're the primary key. Check for them if the object exists.

You can declare a composite primary key using one of two annotations: @IdClass or @EmbeddedId. For more details, have a look at Compound Primary Keys with Hibernate and JPA Annotations.

But if you want to be able to insert two persons with the same firstname/lastname and different address, you'll have to include the address in the key.

Note that it is a best practice to have a numeric surrogate primary key, that is, a primary key that serves only as an identifier and has no business meaning in the application.

Pascal Thivent
the person is only an example. but in this case I would NOT like to insert two persons with the same firstname/lastname - I would like to check if a person with that firstname/lastname couple exists and if yes, do NOT insert but check if the address have to be updated.
swalkner
Oh, ok, I see. Then you just need the firstname/lastname in the compound key.
Pascal Thivent
but how do I compare these "three" steps? 1. check if object exists (comparing the compound keys; in the example: firstname/lastname). 2a.) object doesn't exist - insert - finisehd. 2b.) object exists - did object change? (compare the object to the one in the database) 3) if object changed - update it
swalkner
Just use `merge()`?
Pascal Thivent
but I should know if the object changed or not; if yes, I'd like to update a lastUpdated column...
swalkner