I am attempting to create a primary key in the format “exp0000001,” “exp0000002,” etc.,
before inserting data into the database. Previously, I used GenericGenerator for this purpose,
but with the release of Hibernate 6.5, this class has been deprecated.
I am currently trying to migrate from GenericGenerator to BeforeExecutionGenerator,
but it is not working as expected. the error occured
“java.sql.SQLIntegrityConstraintViolationException: Column ‘file_id’ cannot be null”
I checked my custom generator class generate method not invoked during save process
through spring-data-repository.
Could you please provide me with some advice or direct me to useful references
that might assist me in resolving this issue?
These are my code for your reference.
Here is one of my entity
@Entity
@IdClass(fileId.class)
@Table(name="attach_file")
public class file {
@Id
@Column(name="file_id")
@CustomId(sequenceName="file_id_seq", prefix="exp", size=10)
private String id;
@Id
@Column(name="file_sn")
private int file_sn;
// And other fields, constructors, and methods...
}
This is my custom annotation
@IdGeneratorType(CustomSequenceGenerator.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.FIELD})
public @interface CustomId {
String sequenceName();
String prefix();
int size() default 10;
}
And this is my custom generator
@Slf4j
public class CustomSequenceGenerator implements BeforeExecutionGenerator {
private static final long serialVersionUID = 3249969613251824762L;
private final String sequenceName, prefix;
private final int size;
public CustomSequenceGenerator(String sequenceName, String prefix, int size) {
this.sequenceName = sequenceName;
this.prefix = prefix;
this.size = size;
}
@Override
public EnumSet<EventType> getEventTypes() {
return Sets.newEnumSet(Arrays.asList(EventType.INSERT), EventType.class) ;
}
@Override
public Object generate(SharedSessionContractImplementor session, Object owner, Object currentValue, EventType eventType) {
log.debug(StringUtil.join("", "sequenceName : " , sequenceName, ", prefix : " , prefix , ", size : " , String.valueOf(size)));
ProcedureCall procedure = session.createStoredProcedureCall("get_next_sequence_value");
procedure.registerParameter("seq_name", String.class, ParameterMode.IN);
procedure.setParameter("seq_name", sequenceName);
procedure.registerParameter("next_value", Long.class, ParameterMode.OUT);
procedure.getOutputs();
Long sequenceValue = (Long)procedure.getOutputParameterValue("next_value");
int remainSize = size - prefix.length();
String result = prefix + StringUtil.Lpad(sequenceValue.toString(), remainSize, "0");
log.debug("Generated value : " + result);
return result;
}
}