Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA SequenceGenerator and GeneratedValue: name / generator property unique only per class?

I use JPA + OpenJPA with PostgreSQL as backend RDBMS. The primary keys of my tables usually consist of a SERIAL / BIGSERIAL column. So PostgreSQL automatically generates IDs for new entries (strategy=GenerationType.IDENTITY).

The annotations of ID property 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 annotations block to several entities, while only modifying the sequenceName value? The sequenceName is different from table to table. But may the SequenceGenerator of all Entities be named myseq or something like that? Or does one have to specify a unique generator name for the SequenceGenerator of each Entity? So that each SequenceGenerator name must be unique in the persistence unit?

Is it possibly a good idea to use the same value used for the sequenceName in the database? So that I'd write something like

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

Any recommendations on how to name the SequenceGenerators?

Many thanks in advance for any suggestions!

Yours, Mr. Snrub

like image 836
MrSnrub Avatar asked Oct 22 '22 17:10

MrSnrub


1 Answers

From the Javadoc for SequenceGenerator, emphasis is mine:

Defines a primary key generator that may be referenced by name when a generator element is specified for the GeneratedValue annotation. A sequence generator may be specified on the entity class or on the primary key field or property. The scope of the generator name is global to the persistence unit (across all generator types).

So you will want to use a unique name for each sequence defined in a persistence unit. On a tangent, your GeneratedValue strategy should be SEQUENCE, as pointed out in a comment above.

like image 53
Perception Avatar answered Oct 27 '22 18:10

Perception