I am new to JPA and databases in general. I was trying to generate entities from tables using JPA tools in Eclipse. There are a number of tables and I am trying to generate entities for all of them at the same time. The JPA tool gives me the following options for Key-generator.
I looked around on Google a bit but could not find much that addresses all the options. What do the options mean?
The JPA specification document provides answers in section 11.1.20, on pages 449 and 450:
The
GeneratedValue
annotation provides for the specification of generation strategies for the values of primary keys. The GeneratedValue annotation may be applied to a primary key property or field of an entity or mapped superclass in conjunction with theId
annotation.The use of the
GeneratedValue
annotation is only required to be supported for simple primary keys.
In case you are not familiar with the Id annotation, here is a quick explanation by Vlad Mihalcea from t/his blog post:
The
@Id
annotation is mandatory for entities, and it must be mapped to a table column that has a unique constraint. Most often, the@Id
annotation is mapped to the Primary Key table column.
The types of primary key generation are defined by the GenerationType
enum:
TABLE, SEQUENCE, IDENTITY, AUTO
The JPA spec gives details on those types as follows:
The
TABLE
generator type value indicates that the persistence provider must assign primary keys for the entity using an underlying database table to ensure uniqueness.
The
SEQUENCE
andIDENTITY
values specify the use of a database sequence or identity column, respectively. The further specification of table generators and sequence generators is described in sections 11.1.48 and 11.1.51.
The
AUTO
value indicates that the persistence provider should pick an appropriate strategy for the particular database. The AUTO generation strategy may expect a database resource to exist, or it may attempt to create one. A vendor may provide documentation on how to create such resources in the event that it does not support schema generation or cannot create the schema resource at runtime.
A well-established and recommended strategy is to chose the SEQUENCE
strategy, if that is supported by the database management system.
Note well, that strictly speaking, there is no NONE
strategy defined in the JPA spec. The corresponding option in the select one menu, depicted in the screenshot, simply expresses that "none" of the four regular types shall be set. This seems to be a fallback to indicate you don’t have chosen your strategy for now. Still, you should pick one from the regular ones.