使用雪花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;
}
}