All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.feingto.cloud.config.idworker.SnowflakeIdentityGenerator Maven / Gradle / Ivy

The newest version!
package com.feingto.cloud.config.idworker;

import com.feingto.cloud.config.annotation.ApplicationContextHold;
import com.feingto.cloud.kit.Identities;
import lombok.NoArgsConstructor;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;

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

/**
 * 雪花算法 Hibernate ID 生成策略
 *
 * @author longfei
 */
@NoArgsConstructor
public class SnowflakeIdentityGenerator implements Configurable, IdentifierGenerator {
    private String prefix = "";

    @Override
    public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
        this.prefix = params.getProperty("prefix");
    }

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) {
        return this.prefix + Optional.ofNullable(ApplicationContextHold.getBean(IdGenerator.class))
                .map(IdGenerator::nextId)
                .orElseGet(Identities::uuid);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy