使用jhipster代码生成器生成的项目,如何修改实体类主键生成策略

问题:

使用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,

    /**
 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值