erupt框架自定主键ID 采用Gitee 雪花算法yitter
- 共 3,269 次检阅

引入雪花算法依赖

        <!--青岛漂移算法ID-->
        <dependency>
            <groupId>com.github.yitter</groupId>
            <artifactId>yitter-idgenerator</artifactId>
            <version>1.0.6</version>
        </dependency>

erupt控制器文件加入自定义主键:

    @Id
    @GeneratedValue(generator = "couponIdGenerator",
            strategy = GenerationType.SEQUENCE)
    @GenericGenerator(
            name = "couponIdGenerator",
            strategy = "com.parkinglot.enshi.tools.CarAutoID" //主键生成类名
    )
    @EruptField
    private Long id;

自定义主键生成类:

package com.parkinglot.enshi.tools;

import com.github.yitter.contract.IdGeneratorOptions;
import com.github.yitter.idgen.YitIdHelper;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

import java.io.Serializable;

@Slf4j
public class CarAutoID implements IdentifierGenerator {

    final static short method = 1;
    public void init() {
        IdGeneratorOptions options = new IdGeneratorOptions();
        options.WorkerIdBitLength = 6;
        options.SeqBitLength = 10;
        options.BaseTime = System.currentTimeMillis();
        options.Method = method;
        options.WorkerId = 1;
        YitIdHelper.setIdGenerator(options);
    }

    public static Long snowflake(){
        return  YitIdHelper.nextId();
    }

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object)
            throws HibernateException {
        return  YitIdHelper.nextId();
    }
}


 

分享到:

这篇文章还没有评论

发表评论