JPA SequenceGenerator and GeneratedValue: name / g

2019-07-03 23:17发布

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

1条回答
戒情不戒烟
2楼-- · 2019-07-03 23:56

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.

查看更多
登录 后发表回答