自定义主键生成策略
- 在entity类上添加注解
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "custom-id") @GenericGenerator(name = "custom-id", strategy = "com.h5page-mapdiy.utils.CustomIDGenerator")
@Column(name = "id")
public Long getId() {
return id;
}
注意:GeneratedValue中的generator要与GenericGenerator中的name相等 上面代码中是"custom-id"
- 在utils包下添加自定义ID生成类
package com.h5page-mapdiy.utils
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentityGenerator;
import java.io.Serializable;
/**
* 自定义ID生成器
* @author liaoguanwang
* @date 2019-03-16 10:33
*/
public class CustomIDGenerator extends UUIDGenerator {
@Override
public Serializable generate(SharedSessionContractImplementor session, Object object) throws MappingException {
SimpleDateFormat simpleDateFormat;
simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
String str = simpleDateFormat.format(date);
Random random = new Random();
int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数
return rannum + str;// 当前时间
}
}
注意:
- 测试的ID是Long类型所以这里继承的是IdentityGenerator类
- 如果ID为String类型的话应该继承 UUIDGenerator 或者 UUIDGenerator