0

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!

Moritz Both
  • 1,598
  • 1
  • 13
  • 21
Aaron Silverman
  • 22,070
  • 21
  • 83
  • 103
  • This has been asked before and there is a suggested solution [here](https://forum.hibernate.org/viewtopic.php?p=2404032). Hope this helps. This post was linked from [this](https://stackoverflow.com/questions/2108178/id-generatedvalue-but-set-own-id-value) stackoverflow questions. – Alex Barnes Sep 11 '11 at 09:57

1 Answers1

4

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?

Moritz Both
  • 1,598
  • 1
  • 13
  • 21
  • This is actually the way I started doing it in my tests after posting this :-P But I am still curious how to explicitly set the value of an autoincrement field. MySQL lets you do it, it would be nice if hibernate had same behavior as MySQL -- using auto value if not provided, otherwise use provided value. Don't think that would be a bug. – Aaron Silverman Sep 10 '11 at 19:23