我有一个表,其 id 列自动递增,还有一个 Java 对象,其 getter 用@GeneratedValue(strategy = GenerationType.AUTO)
. 这在保存时效果很好,但是对于单元测试,我想指定 ID 以便它是确定性的。在 MySQL(我们正在使用的数据库)中,我可以在 insert 语句中指定一个值,一切正常。但是,如果我在 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
在此先感谢您帮助我成为一名优秀的测试驱动开发人员!