-
Notifications
You must be signed in to change notification settings - Fork 4
@Id management
JFleet does not manage the Primary Key (@Id
) of your entities like other ORMs do and you are responsible of it. You have some strategies to deal with it:
-
Use the mechanism provided by each database to autogenerate primary keys:
- MySQL: AUTO_INCREMENT attribute
- PostgreSQL: SERIAL numeric type
-
Assign manually an Id to each object:
- Use an UUID generator
- If your domain allows it, use a natural key
- Use a composite key as primary key if the domain also allows it
- If you control the concurrency access to the table, at the beginning of insertion process, get the max Id value in database and, from Java, increment and set a new Id value to each object
If you opt for an autogenerate strategy, breaking the JPA specification, you can avoid creating a field with the @Id column because it will be always null. But you can keep it if you want, or you are reusing a class from a existing JPA model.
In an autogenerate strategy, ORMs like JPA populate the @Id field of your objects as they insert rows in the database. But due to the insertion technique used by JFleet, primary keys created by the database can not be retrieved for each inserted row, and is not possible to set it back to each object.
In PostgreSQL, if you have a field in an entity which the corresponding database column is declared as SERIAL
, you must annotate the field with @Id
and @GeneratedValue(strategy = GenerationType.IDENTITY)
. Otherwise JFleet will try to insert a null value and the database will raise an error. Internally SERIAL
is an alias to NOT NULL with a DEFAULT value implemented as a sequence, and does not accept to insert a null value, even when afterwards it will assign one.
JFleet needs to know if a field is SERIAL
, and the convention used is annotating it with IDENTITY
strategy.