Calling next value of a sequence in jpa

I just want to have a method which call nextval on a sequence associated with "code" field, and returns the value. What's the best way to do it in JPA with annotations?

  • Use native SQL to get the next sequence value when the user pushes the button. Either create the sequence manually or use a "fake entity" to have JPA create it for you.
  • If you don't want to use native SQL, insert an entity relying on the sequence and gets its id.

Both solutions sounds a bit ugly. Maybe you could simply use a random generator like a UUID generator.

Actually, you didn't mention anything about the uniqueness of the code (and the JPA annotations don't show it must be unique). Why don't you return a random int?