主键生成的策略---雪花id

使用雪花ID,在新增商品的时候就不需要去管主键这个属性了

1.写一个SnowflowID 类

package com.id;

import cn.hutool.core.util.IdUtil;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;

import java.io.Serializable;
import java.math.BigDecimal;

/**
 * 雪花ID生成
 */
public class SnowflowID implements  org.hibernate.id.IdentifierGenerator{
    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
        Long id = IdUtil.getSnowflake(0,0).nextId();
        return id;
    }
}

2.在pojo类上面加
@GenericGenerator(name=“snowFlow”,strategy = “com.id.SnowflowID”) //注册雪花id
com.id.SnowflowID是SnowflowID类所在路径
在主键上加
@Id
@GeneratedValue(generator = “snowFlow”) // 使用雪花id

package com.pojo;


import lombok.Data;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.math.BigDecimal;

@Entity
@GenericGenerator(name="snowFlow",strategy = "com.id.SnowflowID")  //注册雪花id
@Data
public class Goods {

  @Id
  @GeneratedValue(generator = "snowFlow") // 使用雪花id
  private long gid;
  private String gName;
  private BigDecimal gPrice;


  public long getGid() {
    return gid;
  }

  public void setGid(long gid) {
    this.gid = gid;
  }


  public String getGName() {
    return gName;
  }

  public void setGName(String gName) {
    this.gName = gName;
  }


  public BigDecimal getGPrice() {
    return gPrice;
  }

  public void setGPrice(BigDecimal gPrice) {
    this.gPrice = gPrice;
  }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值