[英]Hibernate: Check if object exists/changed
Assuming I have an object Person with 假设我有一个对象Person
long id
String firstName
String lastName
String address
Then I'm generating a Person-object somewhere in my application. 然后,我在应用程序中的某个位置生成了一个Person对象。 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. 我想使用注释,好像说:firstname / lastname =>它们是主键。 Check for them if the object exists.
检查对象是否存在。
address is the parameter you have to compare if it stayed the same or not. address是您必须比较的参数,如果它保持不变。
Does Hibernate/JPA (or another framework) support something like that? Hibernate / JPA(或其他框架)是否支持类似的东西?
pseude-code: pseude代码:
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.
我想使用注释,好像说:firstname / lastname =>它们是主键。 Check for them if the object exists.
检查对象是否存在。
You can declare a composite primary key using one of two annotations: @IdClass
or @EmbeddedId
. 您可以使用以下两个注释之一声明一个复合主键:
@IdClass
或@EmbeddedId
。 For more details, have a look at Compound Primary Keys with Hibernate and JPA Annotations . 有关更多详细信息,请参阅带有Hibernate和JPA批注的复合主键 。
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. 请注意,最佳实践是使用数字代理主键,即,该主键仅用作标识符,在应用程序中没有业务意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.