Skip to main content

Key Generation

PostgreSQL commonly generates primary keys with SERIAL, BIGSERIAL, IDENTITY, or a sequence. The first three generate the value during INSERT and dbVisitor writes it back to the entity. A sequence can also be read before INSERT.

Note

For general configuration, see Generated Keys.

Key Strategies

StrategyUsage on this datasource
AssignedSupply the primary key before insertion.
Auto-incrementUse a database-generated numeric key.
UUIDUse UUID32 or UUID36 with a string key field.
SequenceFetch a sequence value before insertion.
CustomUse a custom generator before or after insertion.

Using SERIAL / IDENTITY

CREATE TABLE user_info (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
name VARCHAR(64),
age INTEGER
)

Use KeyType.Auto on the entity key:

@Table("user_info")
public class UserInfo {
@Column(value = "id", primary = true, keyType = KeyType.Auto)
private Long id;

private String name;
private Integer age;
}

The Builder API generates the INSERT from the entity mapping and writes the PostgreSQL-generated key to the current entity.

UserInfo user = new UserInfo();
user.setName("mali");
user.setAge(18);

LambdaTemplate lambda = ...;
int rows = lambda.insert(UserInfo.class)
.applyEntity(user)
.executeSumResult();

Long id = user.getId();
Note

Rows skipped by Ignore have no returned ID. See Insert Conflicts for handling existing records.

Using a Sequence

This example uses a regular primary-key column and a sequence, independently of the identity example above:

CREATE TABLE user_info (
id BIGINT PRIMARY KEY,
name VARCHAR(64),
age INTEGER
);
CREATE SEQUENCE user_info_id_seq START WITH 1 INCREMENT BY 1;
import net.hasor.dbvisitor.mapping.Column;
import net.hasor.dbvisitor.mapping.KeySeq;
import net.hasor.dbvisitor.mapping.KeyType;
import net.hasor.dbvisitor.mapping.Table;

@Table("user_info")
public class UserInfo {
@Column(primary = true, keyType = KeyType.Sequence)
@KeySeq("user_info_id_seq")
private Long id;
private String name;
private Integer age;

// Getters and setters omitted
}
UserInfo user = new UserInfo();
user.setName("mali");

lambda.insert(UserInfo.class)
.applyEntity(user)
.executeSumResult();

Long id = user.getId();

Each insert obtains a sequence value, assigns it to id, and inserts the row.