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!