[JAVA] [Spring Data JPA] Custom ID is assigned in a unique sequence at the time of registration.

Introduction

When registering data with "Spring Data JPA" This is a summary of the codes when prefixes are added to the numbers assigned in the sequence.

environment

Java 8 PostgreSQL 10.5

What i did

Implement your own Generator. (Prefixer)

Inherits SequenceStyleGenerator. Numbering in the sequence uses the internal (superclass) processing as it is. The original Generator is the role of prefixing the numbered ones.

Describe Generator specification and parameters in Entity

Specify the sequence, prefix, and format in Entity. If you do not specify a sequence, it will try to use hibernate_sequence. (I was a little addicted here)

Source

The implemented source.

Original Generator

python


import java.io.Serializable;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
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 PrefixedIdGenerator extends SequenceStyleGenerator {

    public static final String VALUE_PREFIX_PARAMETER = "valuePrefix";
    public static final String VALUE_PREFIX_DEFAULT = "";
    private String valuePrefix;


    public static final String NUMBER_FORMAT_PARAMETER = "numberFormat";
    public static final String NUMBER_FORMAT_DEFAULT = "%d";

    private String numberFormat;

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        return valuePrefix + String.format(numberFormat, super.generate(session, object));
    }

    @Override
    public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
        super.configure(LongType.INSTANCE, params, serviceRegistry);
        valuePrefix = ConfigurationHelper.getString(VALUE_PREFIX_PARAMETER, params, VALUE_PREFIX_DEFAULT);
        numberFormat = ConfigurationHelper.getString(NUMBER_FORMAT_PARAMETER, params, NUMBER_FORMAT_DEFAULT);
    }
}

Entity

python


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.Data;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Data
@Table(name = "trial")
public class Trial {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_trial")
    @GenericGenerator(
            name = "seq_trial",
            strategy = "PrefixedIdGenerator",
            parameters = {
                @Parameter(name = PrefixedIdGenerator.SEQUENCE_PARAM, value = "seq_trial"),
                @Parameter(name = PrefixedIdGenerator.VALUE_PREFIX_PARAMETER, value = "B_"),
                @Parameter(name = PrefixedIdGenerator.NUMBER_FORMAT_PARAMETER, value = "%05d") })
    @Column(name = "trial_id")
    private String trialId;

    @Column(name = "trial_name")
    private String trialName;
}

Service

python


@Service
public class TrialService {

    @Autowired
    private TrialRepository repository;

    @Transactional
    public void insert() {

        Trial entity = new Trial();
        entity.setTrialName("trial_xxxxxxxx");

        repository.save(entity);
    }
}

Runtime log

2019/05/24 17:54:18.505 [http-nio-8099-exec-1] DEBUG SqlStatementLogger 92 : 
    select
        nextval ('seq_test')
2019/05/24 17:54:22.313 [http-nio-8099-exec-1] DEBUG SqlStatementLogger 92 : 
    insert 
    into
        trial
        (trial_name, trial_id) 
    values
        (?, ?)
2019/05/24 17:54:22.318 [http-nio-8099-exec-1] TRACE BasicBinder 65 : binding parameter [1] as [VARCHAR] - [trial_xxxxxxxx]
2019/05/24 17:54:22.319 [http-nio-8099-exec-1] TRACE BasicBinder 65 : binding parameter [2] as [VARCHAR] - [B_00001]

Referenced site

How to Implement a Custom, Sequence-Based ID Generator

that's all

Recommended Posts

[Spring Data JPA] Custom ID is assigned in a unique sequence at the time of registration.
Spring Data JPA: Write a query in Pure SQL in @Query of Repository
How to make a unique combination of data in the rails intermediate table
Until the use of Spring Data and JPA Part 2
Until the use of Spring Data and JPA Part 1
Make the where clause variable in Spring Data JPA
Check the behavior of getOne, findById, and query methods in Spring Boot + Spring Data JPA
[Spring Data JPA] Can And condition be used in the automatically implemented method of delete?
Determine that the value is a multiple of 〇 in Ruby
No property list found for type because it is a non-named query of Spring Data JPA
Generate a serial number with Hibernate (JPA) TableGenerator and store it in the Id of String.
Get a proxy instance of the component itself in Spring Boot
See the behavior of entity update with Spring Boot + Spring Data JPA
What you are doing in the confirmation at the time of gem update
[Spring Boot] Post files and other data at the same time [Axios]
Email sending function with Action Mailer at the time of new registration
How to change the value of a variable at a breakpoint in intelliJ
How to implement the email authentication function at the time of user registration
The story of encountering Spring custom annotation
The identity of params [: id] in rails
Exists using Specification in Spring Data JPA
What is the data structure of ActionText?
[Rails 6] Change redirect destination at the time of new registration / login by devise
How to get the ID of a user authenticated with Firebase in Swift
Sign in to a Spring Boot web application on the Microsoft ID platform
Get the path defined in Controller class of Spring boot as a list
Jackson is unable to JSON serialize hibernateLazyInitializer in Spring Data JPA with error
Even if I want to convert the contents of a data object to JSON in Java, there is a circular reference ...
When displaying a message with a JSF custom validator, the errorClass of h: message is not applied unless SEVERITY_ERROR is set in the message.