Generate sequential number in java with Hibernate

6

Is there any way to use Hibernate to generate a custom number to be the ID number of a particular record?

I have a system that stores care done to a patient, every time a new care is created is generated by the bank auto increment the numbering of this registry, however I would like to have a more compound number type generated: (Year - Month - Day - Hour - Minute - AutoIncrement Id)

My id is mapped like this:

@Id
@GeneratedValue
public Long getRegistro() {
    return registro;
}

I would like to customize this GeneratedValue, is this possible? I looked over this but I was a little confused how to do it, I'm still a beginner with Hibernate.

    
asked by anonymous 28.02.2016 / 18:39

2 answers

0

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

    
27.12.2018 / 00:17
1

A entity:

@Entity
public class Carro {

    @Id
    @GenericGenerator(name = "geradorId", strategy = "com.example.GeradorIDCarro")
    @GeneratedValue(generator = "geradorId")
    private String id;

    @Column
    private String modelo;

    @Column
    private int ano;

    // getters and setters
}

And the class that generates the custom ID:

package com.example;

import java.io.Serializable;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.IdentifierGenerator;

public class GeradorIDCarro implements IdentifierGenerator {
    @Override
    public Serializable generate(SessionImplementor session, Object object)
            throws HibernateException
    {
        final Carro entity = (Carro) object;
        return entity.getModelo() + '-' + entity.getAno();
    }
}

Reference .

    
30.08.2017 / 20:32