java JPA @Version:如何使用它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1838646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 18:12:25 来源:igfitidea点击:
JPA @Version: how to use it?
提问by cometta
@Entity
public class Person {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private int salary;
@Version
private long version;
// ...getters and setters
}
- Is it required to create setter/getter for
version? - When persisting this entity with Hibernate, I don't need to set this value manually, right?
- What else do I need to configure in order to use optimistic concurrency checking with Spring's
hibernateTemplate.saveOrUpdate? Are all databases supported? - How to unit-test this entity? In my database all my records showing version field have value of 0
- Will calling
hibernateTemplate.saveOrUpdateincrement the version value every time?
- 是否需要为其创建 setter/getter
version? - 当使用 Hibernate 持久化这个实体时,我不需要手动设置这个值,对吧?
- 为了使用 Spring 的乐观并发检查,我还需要配置
hibernateTemplate.saveOrUpdate什么?是否支持所有数据库? - 如何对这个实体进行单元测试?在我的数据库中,所有显示版本字段的记录的值为 0
hibernateTemplate.saveOrUpdate每次调用都会增加版本值吗?
采纳答案by KLE
I would say:
我会说:
- set/get version is required, as you might assign the version yourself sometimes (when recreating an new instance from old data)
- You don't need if you read the instance from the database. (When creating it in your code with new, it would be a different story).
- I see nothing else. I never had a problem with a database.
- Unit test don't go the database in my opinion, so tests involving the database are called integration tests. You shouldn't have too much of them, as they are slow, and they don't really test your code, but more the Hibernate/Driver/Database codes ... You should trust them, or just test them once, but not for all your entities.
To see version values more than 0, read/modify/update your entity in a transaction, the version increase by one. Go out of the transaction, do it again, the value increases ... - The version will increase each time the database row is modified.
- 需要设置/获取版本,因为有时您可能会自己分配版本(从旧数据重新创建新实例时)
- 如果从数据库中读取实例,则不需要。(在您的代码中使用 new 创建它时,情况会有所不同)。
- 我什么也看不到。我从来没有遇到过数据库问题。
- 在我看来,单元测试不涉及数据库,因此涉及数据库的测试称为集成测试。你不应该有太多它们,因为它们很慢,而且它们并没有真正测试你的代码,但更多的是 Hibernate/Driver/Database 代码......你应该相信它们,或者只测试它们一次,但不要对于您的所有实体。
要查看大于 0 的版本值,请在事务中读取/修改/更新您的实体,版本增加一。退出交易,再做一次,价值增加...... - 每次修改数据库行时,版本都会增加。

