Skip to content
Guillaume Le Cousin edited this page Dec 5, 2021 · 2 revisions

Ids

Primary key

A primary key is identified on an entity using the Spring @Id annotation.

@Table
public class Entity {

  @Id
  private Long id;

}

Generated primary key

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 sequence to generate the next value, the sequence name can be specified using the sequence attribute on the annotation
  • RANDOM_UUID to generate a random UUID

Composite 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
  • properties name 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;

	[...]
}

Clone this wiki locally