Calling next value of a sequence in jpa

前端 未结 2 1272
情书的邮戳
情书的邮戳 2021-01-12 10:11

I have a class mapped as an Entity to persist it in a database. I have an id field as the primary key so every time the object is persisted the value of the id is retrieved

相关标签:
2条回答
  • 2021-01-12 10:52

    See another question/answers on the subject of using sequence defined elsewhere than id fields. You can create a fake entity with one field (of type Long id). Connect it to the sequence you defined in the DB. Then create a CrudRepository implementation for that entity and call its save() method with an empty instance of the fake entity object you defined. Hibernate will run for you a "select YOUR_SEQ.NEXTVAL from dual" query.

    0 讨论(0)
  • 2021-01-12 10:53

    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?

    0 讨论(0)
提交回复
热议问题