-
Notifications
You must be signed in to change notification settings - Fork 12
Ids
Guillaume Le Cousin edited this page Dec 5, 2021
·
2 revisions
A primary key is identified on an entity using the Spring @Id annotation.
@Table
public class Entity {
@Id
private Long id;
}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 -
SEQUENCEto use a sequence to generate the next value, the sequence name can be specified using thesequenceattribute on the annotation -
RANDOM_UUIDto generate a random UUID
When several columns must be used as primary key, the @CompositeId annotation can be used, specifying the 2 attributes:
-
indexNamename of the index to create on the columns -
propertiesname of attributes on the entity class to use
For example, a company's Site is defined by the company id and the postal address id:
@Table
@CompositeId(indexName = "siteId", properties = { "company", "address" })
public class Site {
@ForeignKey(optional = false, onForeignDeleted = OnForeignDeleted.DELETE)
private Company company;
@ForeignKey(optional = false, onForeignDeleted = OnForeignDeleted.DELETE, cascadeDelete = true)
private PostalAddress address;
@Column
private String name;
[...]
}