-
Notifications
You must be signed in to change notification settings - Fork 12
Ids
A primary key is identified on an entity using the Spring @Id
annotation.
@Table
public class Entity {
@Id
private Long id;
}
A primary key may be any type supported by the database (numbers, string, UUID, dates...).
An additional @GeneratedValue
annotation can be used to ask the database to automatically generate the value:
@Table
public class Entity {
@Id @GeneratedValue
private Long id;
}
There are 3 generation strategies available, using the strategy
attribute on the annotation:
-
AUTO_INCREMENT
(default) to automatically increment the value -
SEQUENCE
to use a database sequence to generate the next value. The sequence name must be specified using thesequence
attribute on the annotation -
RANDOM_UUID
to generate a random UUID if supported by the database (PostgreSQL needs to configure the extension uuid-ossp).
Example for a sequence:
@Table
public class Entity {
@Id @GeneratedValue(strategy = Strategy.SEQUENCE, sequence = "my_sequence")
private Long id;
}
Example for a random UUID:
@Table
public class Entity {
@Id @GeneratedValue(strategy = Strategy.RANDOM_UUID)
private UUID id;
}
When several columns must be used as primary key, the @CompositeId
annotation can be used, specifying the 2 attributes:
-
indexName
name of the index to create on the columns (used only for schema generation) -
properties
name of attributes on the entity class to use
Here is an example with a table population where we want to use the date and the city as primary key:
@Table
@CompositeId(indexName = "population_key", properties = { "date", "city" })
public class Population {
@Column
private LocalDate date;
@Column
private String city;
@Column
private Long population;
[...]
}
Note: Any type of column may be used, including foreign keys.
Next step is to link tables, with one-to-one, one-to-many and many-to-many Relationships.