集成hibernate和雪花id
1、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.5.7.Final</version>
</dependency>
2、添加配置 指定数据源和hivernate 方言配置
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/dh-home?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: root
jpa:
hibernate:
ddl-auto: update
show-sql: true
database: mysql
generate-ddl: true
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
3、实体添加@Entity
@Entity
@Table(name = Constants.SYS_+"user")
@TableName(value = Constants.SYS_+"user")
@Data
public class User extends BaseEntity {
@Column(columnDefinition = "varchar(255) comment '姓名' ")
private String name;
@Column(columnDefinition = "varchar(255) comment '密码' ")
private String password;
}
雪花id生成
1、指定id生成策略
@Id
@GenericGenerator(name = "snowFlakeIdGenerator", strategy = "com.ayou.shunfengche.config.SnowFlakeIdGenerator")
@GeneratedValue(generator = "snowFlakeIdGenerator")
@Column(name = "id", length=18)
private Long id;
2、添加雪花id生成类:
package com.ayou.shunfengche.config;
import javax.annotation.PostConstruct;
import org.hibernate.HibernateException;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* 雪花算法
*/
@Component
public class SnowFlake implements ApplicationContextAware {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger(SnowFlake.class);
private static ApplicationContext _applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SnowFlake._applicationContext = applicationContext;
}
public static SnowFlake getBean() {
return _applicationContext.getBean(SnowFlake.class);
}
/**
* 起始的时间戳
*/
private final long twepoch = 1557825652094L;
/**
* 每一部分占用的位数
*/
private final long workerIdBits = 5L;
private final long datacenterIdBits = 5L;
private final long sequenceBits = 12L;
/**
* 每一部分的最大值
*/
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
private final long maxSequence = -1L ^ (-1L << sequenceBits);
/**
* 每一部分向左的位移
*/
private final long workerIdShift = sequenceBits;
private final long datacenterIdShift = sequenceBits + workerIdBits;
private final long timestampShift = sequenceBits + workerIdBits + datacenterIdBits;
@Value("${snowflake.datacenter-id:1}")
private long datacenterId; // 数据中心ID
@Value("${snowflake.worker-id:0}")
private long workerId; // 机器ID
private long sequence = 0L; // 序列号
private long lastTimestamp = -1L; // 上一次时间戳
@PostConstruct
public void init() {
String msg;
if (workerId > maxWorkerId || workerId < 0) {
msg = String.format("worker Id can't be greater than %d or less than 0", maxWorkerId);
LOG.unsuccessful(msg);
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
msg = String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId);
LOG.unsuccessful(msg);
}
}
public Long nextIdString() {
long id = nextId();
return id;
}
public synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new HibernateException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (timestamp == lastTimestamp) {
sequence = (sequence + 1) & maxSequence;
if (sequence == 0L) {
timestamp = tilNextMillis();
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
return (timestamp - twepoch) << timestampShift // 时间戳部分
| datacenterId << datacenterIdShift // 数据中心部分
| workerId << workerIdShift // 机器标识部分
| sequence; // 序列号部分
}
private long tilNextMillis() {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
}
package com.ayou.shunfengche.config;
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.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;
/**
* JPA 雪花算法ID生成器
*/
public class SnowFlakeIdGenerator implements IdentifierGenerator, Configurable {
@Override
public Serializable generate(SharedSessionContractImplementor session, Object o) throws HibernateException {
return SnowFlake.getBean().nextIdString();
}
@Override
public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
}
}
自此完成配置,调用mybaits-plus的save 方法生成如下: