An alternative solution would be to use @GeneratorType.
With this annotation, you can provide a custom implementation during insert and update of the hosting entity. In this case, adding a sequence
First create this sequence and add it during the creation or altering of the table:
CREATE SEQUENCE project_code_seq INCREMENT 1 START 1;
ALTER TABLE project
ADD COLUMN key bigint NOT NULL DEFAULT nextval('project_code_seq');
Create a class that implements the ValueGenerator:
public class ProjectCodeGenerator implements ValueGenerator<Long> {
private static final String SELECT_NEXTVAL = "select nextval('project_code_seq')";
@Override
public Long generateValue(Session session, Object object) {
if (object instanceof ProjectEntity project) {
var result = (BigInteger) session.createNativeQuery(SELECT_NEXTVAL)
.setHibernateFlushMode(
FlushMode.COMMIT).getSingleResult();
return result.longValue();
} else {
throw new RuntimeException("Can only be used for " + ProjectEntity.class);
}
}
}
Then on the entity you can add the @GeneratorType annotation:
@GeneratorType(type = ProjectCodeGenerator.class, when = GenerationTime.INSERT)
private Long code;
Note that the ProjectCodeGenerator can be tuned to whatever you desire and more logic can be added.