JPA SequenceGenerator and GeneratedValue: is the name / generator property unique for each class only?

I am using JPA + OpenJPA with PostgreSQL as fallback RDBMS. The primary keys of my tables usually consist of the SERIAL

/ column BIGSERIAL

. Therefore PostgreSQL will automatically generate identifiers for new records ( strategy=GenerationType.IDENTITY

).

The ID property annotations look like this:

@Id
@SequenceGenerator(name="myseq",sequenceName="foobartable_fooid_seq")
@GeneratedValue(generator="myseq",strategy=GenerationType.IDENTITY)

      

My question is, can I copy and paste this annotation block to multiple entities, only changing the value sequenceName

? sequenceName

differs from table to table. But can the SequenceGenerator of all Entities be named myseq

or something like that? Or do you need to provide a unique generator name for the SequenceGenerator for each object? So, each SequenceGenerator name must be unique in the save unit?

Is it possible to use the same values ​​as for sequenceName in the database? So that I write something like

@Id
@SequenceGenerator(name="foobartable_fooid_seq",sequenceName="foobartable_fooid_seq")
@GeneratedValue(generator="foobartable_fooid_seq",strategy=GenerationType.IDENTITY)

      

Any guidance on how to name the SequenceGenerators?

Thanks a lot in advance for any suggestions!

Best regards, Mr. Snrub

+3


source to share


1 answer


From the Javadoc for SequenceGenerator

, emphasis mine:

Defines a primary key generator that can be referenced by name when a generator element is specified for the GeneratedValue annotation. the sequence generator can be specified on an entity class or on primary key or property fields. The generator name scope is global for the persistence unit (for all generator types).



Thus, you will want to use a unique name for each sequence defined in the save module. Tangentially, your strategy GeneratedValue

should be SEQUENCE as mentioned in the comment above.

+2


source







All Articles