Bypass GeneratedValue in Hibernate
Asked Answered
A

1

11

Is it possible to bypass @GeneratedValue for an ID in Hibernate, we have a case where, most of the time we want the ID to be set using GeneratedValue, but in certain cases would like to set the ID manually.

Is this possible to do?

Adrianadriana answered 18/9, 2008 at 2:20 Comment(0)
A
5

I know you can do this in the JPA spec, so you should be able to in Hibernate (using JPA+ annotations).

If you just fill in the ID field of the new persistent model you're creating, then when you "Merge" that model into the EntityManager, it will use the ID you've set.

This does have ramifications, though. You've just used up that ID, but the sequence specified by the GeneratedValue annotation doesn't know that. Unless you're specifying an ununsed ID that's LESS than the current sequence value, you're going to get a problem once the sequence catches up to the value you just used.

So, maybe I can see where you might want the user to be able to specify an ID, but then you need to catch the possible Exception (duplicate ID) that may come in the future.

Angulate answered 18/9, 2008 at 3:23 Comment(3)
In my case, there would be no duplicate, as the ID would be generated from the same sequence in both cases, just at different points in the transaction.Adrianadriana
I have a doubt about this, see questions like #3195221 and #2108678.Goring
I don't think this is correct either. It certainly does not work in hibernate and I also have doubts that this would work with most JPA providers.Hades

© 2022 - 2024 — McMap. All rights reserved.