I know the question is very old but recently I found a solution that solved my difficulty now, I'll leave it here, maybe someone will need it one day.
How to declare the field that will have the numbering generated
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "registro_seq")
@GenericGenerator(name = "registro_seq", strategy = "br.com.pegasus.util.RegistroPrefixedSequenceIdGenerator", parameters = {
@Parameter(name = RegistroPrefixedSequenceIdGenerator.INCREMENT_PARAM, value = "1") })
private String registro;
Generator Format Class (RecordPrefixedSequenceIdGenerator)
import java.io.Serializable;
import java.time.LocalDate;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.enhanced.SequenceStyleGenerator;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.LongType;
import org.hibernate.type.Type;
public class RegistroPrefixedSequenceIdGenerator extends SequenceStyleGenerator {
public static final String DATE_FORMAT_PARAMETER = "dateFormat";
public static final String DATE_FORMAT_DEFAULT = "%tY";
public static final String NUMBER_FORMAT_PARAMETER = "numberFormat";
public static final String NUMBER_FORMAT_DEFAULT = "%05d";
public static final String DATE_NUMBER_SEPARATOR_PARAMETER = "dateNumberSeparator";
public static final String DATE_NUMBER_SEPARATOR_DEFAULT = "0";
private String format;
@Override
public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
return String.format(format, LocalDate.now(), super.generate(session, object));
}
@Override
public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
// TODO Auto-generated method stub
super.configure(LongType.INSTANCE, params, serviceRegistry);
String dateFormat = ConfigurationHelper.getString(DATE_FORMAT_PARAMETER, params, DATE_FORMAT_DEFAULT)
.replace("%", "%1$");
String numberFormat = ConfigurationHelper.getString(NUMBER_FORMAT_PARAMETER, params, NUMBER_FORMAT_DEFAULT)
.replace("%", "%2$");
;
String dateNumberSeparator = ConfigurationHelper.getString(DATE_NUMBER_SEPARATOR_PARAMETER, params,
DATE_NUMBER_SEPARATOR_DEFAULT);
this.format = dateFormat + dateNumberSeparator + numberFormat;
}
}
Required in the database to have this table, which will control the generation of the next number to be generated.
Table in the bank
CREATE TABLE hibernate_sequence (
next_val BIGINT(20)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO hibernate_sequence VALUE(1);
That's it, with this change you can generate a custom number for the ID
The solution was not developed by me, but after a long time trying to find something that solved my previous doubts of years ago, I leave the link of the source, all credits for the solution belongs to the author.
Source: link