开发者

Hibernate: Check if object exists/changed

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);
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜