Java/Hibernate: How can I insert a specific value for a column with autoincrement / @GeneratedValue
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, howeve开发者_如何学运维r 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!
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 your daoForMyObject.persist()
calls save()
, so right after that you can read the id:
MyObject myObject = new MyObject();
myObject.setStr("this does work.");
daoForMyObject.persist(myObject);
Long id = myObject.getId();
Now use id
to reference your entity instead of 10... why should you not be able to do it this way?
精彩评论