0

In Hibernate is there a way to skip generating the value of a @GeneratedValue property by manually setting it before calling save on the session?

I am building an import/export facility and I would like to preserve the IDs from a previously made export.

Jon Tirsen
  • 4,750
  • 4
  • 29
  • 27
  • Does this answer your question? [Bypass GeneratedValue in Hibernate (merge data not in db?)](https://stackoverflow.com/questions/3194721/bypass-generatedvalue-in-hibernate-merge-data-not-in-db) – Dinei Apr 19 '22 at 14:26

4 Answers4

2

Is important to say, if you use this way:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

And you don't have the id you set in the database it will ignore your id set and the database will create a new one. I mean, if you have an empty database and set user.setId(100L) and save, when you find it in database the service.findById(100L) will not find any object.

Luiz Rossi
  • 772
  • 5
  • 19
0

By default, Hibernate won't override value if it was already set, so everything should work as you expect. Just make sure you're not using AUTO.

If you need a more complex logic, take a look at @GenericGenerator. https://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-identifier

Alexey Soshin
  • 16,718
  • 2
  • 31
  • 40
  • Interesting... For some reason it does still try to generate the ID. Something else is probably not working properly. I'll keep digging. – Jon Tirsen Oct 17 '16 at 10:51
  • Well there you go, if you explicitly set it to "IDENTITY" then it works! Why, I don't understand... – Jon Tirsen Oct 17 '16 at 11:26
  • AUTO should switch to IDENTITY on MySQL. Check that you specified MySQL dialect in your Hibernate config. – Alexey Soshin Oct 17 '16 at 11:29
0

@GeneratedValue will only apply it's strategy if the id on which you're applying this annotation is null/0.

This means that if you've manually assigned an id field, then @GeneratedValue annotation is USELESS.

Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
0

The problem is that I was using the default (AUTO) strategy for the @GeneratedValue. If I change it to explicitly specify IDENTITY then it works!

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

I don't really understand why though... :-)

Jon Tirsen
  • 4,750
  • 4
  • 29
  • 27