Java/Hibernate:如何为具有自动增量/@GenerateValue 的列插入特定值
我有一个表,其中包含自动递增的 id 列,以及一个 Java 对象,该对象具有用 @GenerateValue(strategy = GenerationType.AUTO) 注释的 getter。这在保存时非常有用,但是对于单元测试,我想指定 ID 以使其具有确定性。在 MySQL(我们正在使用的数据库)中,我可以在插入语句中指定一个值,一切正常。但是,如果我在 java 对象中设置 id 字段并尝试保留,hibernate 会抛出异常。如何让 Hibernate 让我为通常生成的值指定一个值?
字段示例:
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return this.id;
}
在 MySQL 中有效:
INSERT INTO myTable (id, str)
VALUES (10,'this works!')
无效:
MyObject myObject = new MyObject();
myObject.setId(10L); //remove this line and hibernate saves ok
myObject.setStr("this does not work.");
daoForMyObject.persist(myObject); //throws org.springframework.dao.DataIntegrityViolationException
预先感谢您帮助我成为一名优秀的测试驱动开发人员!
I have a table with an id column that autoincrements, and a Java object that has a getter annotated with @GeneratedValue(strategy = GenerationType.AUTO)
. This works great when saving, however for a unit test I want to specify the ID so that it is deterministic. In MySQL (the DB we are using) I can specify a value in the insert statement and everything works fine. However if I set the id field in the java object and try to persist, hibernate throws an exception. How can I allow Hibernate to let me specify a value for a typically generated value?
Field Example:
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return this.id;
}
Works in MySQL:
INSERT INTO myTable (id, str)
VALUES (10,'this works!')
Does not work:
MyObject myObject = new MyObject();
myObject.setId(10L); //remove this line and hibernate saves ok
myObject.setStr("this does not work.");
daoForMyObject.persist(myObject); //throws org.springframework.dao.DataIntegrityViolationException
Thanks in advance for helping me be a good test-driven developer!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我很抱歉以您可能不想要的方式回答,但我认为您的想法很糟糕。如果您的目标是成为一名优秀的测试驱动开发人员,请不要这样做。你基本上是在破坏你想要测试的东西。您要求您的设备在测试时采取特殊行为。但单元测试应该按原样测试单元。
如果 hibernate 允许您为自动增量(或其他)字段设置固定值,则这可能被视为 hibernate 中的错误。在我看来,休眠状态不允许这样做是件好事。
为什么不在
session.save()
方法调用后读取 id 值?可能您的daoForMyObject.persist()
调用save()
,因此您可以立即读取 id:现在使用
id
来引用您的实体而不是 10...为什么你不能这样做呢?I'm sorry to answer in a way you probably don't want, but I think your idea is bad. If your goal is to be a good test-driven developer, don't do this. Your are basically sabotaging what you want to test. You request a special behaivour from your unit when under test. But a unit test should test the unit as it is.
If hibernate would let you set a fixed value for a autoincrement (or so) field, this could be considered a bug in hibernate. As I see it, it is good that hibernate does not allow it.
Why don't you read the id value after the
session.save()
method call? Probably yourdaoForMyObject.persist()
callssave()
, so right after that you can read the id:Now use
id
to reference your entity instead of 10... why should you not be able to do it this way?