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

依然范特西╮ 提交于 2019-12-10 19:35:31

问题


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:


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.



来源:https://stackoverflow.com/questions/14762483/jpa-sequencegenerator-and-generatedvalue-name-generator-property-unique-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!