问题:
使用jhipster中的【jdl工具】可以快速生成 实体类。但是默认生成的【实体类的主键】是Long类型的,自增。如果想要换一种其他的生成策略,比如 想要变成Long类型的,但不是自增型的,使用snowflake算法生成的id,该如何解决呢?
步骤:
1. 在想要修改id生成策略的domain中,通常会看到如下所示的情况
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
2. 将之改成如下
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "custom-id")
@GenericGenerator(name="custom-id", strategy = "com.test.user.util.CustomIdGenerator")
private Long id;
3. 添加自定义策略的Generator类
package com.test.user.util;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentityGenerator;
import java.io.Serializable;
public class CustomIdGenerator extends IdentityGenerator {
@Override
public Serializable generate(SharedSessionContractImplementor s, Object obj) {
/*
* 生成id的代码,下面的1和2自定义
*/
// 1.使用TwitterUtil生成id
TwitterUtil util = new TwitterUtil(0, 0);
Long id = util.nextId();
// 2.使用UUID生成id
// String id = UUID.randomUUID().toString();
if(null != id){
return (Serializable) id;
}
return super.generate(s, obj);
}
}
说明:
1. 看一下GenerationType,可知为什么选择GenerationType.AUTO
package javax.persistence;
/**
* Defines the types of primary key generation strategies.
*
* @see GeneratedValue
*
* @since Java Persistence 1.0
*/
public enum GenerationType {
/**
* Indicates that the persistence provider must assign
* primary keys for the entity using an underlying
* database table to ensure uniqueness.
*/
TABLE,
/**