欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

自定义主键生成器

程序员文章站 2022-07-13 09:19:35
...

1. 编写MyIdGenerator

  • 这是我们自己的id生成器,首先要继承org.hibernate.id.IdentifierGenerator接口,并实现generate方法,方法返回值即是生成的id
package com.example.springboot.mysqldemo.util;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

import java.io.Serializable;
import java.util.UUID;

public class MyIdGenerator implements IdentifierGenerator {

    public static final String TYPE = "com.example.springboot.mysqldemo.util.MyIdGenerator";

    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
    	// 简单示例
        String uuid= UUID.randomUUID().toString();
        System.out.println("my:"+uuid);
        return "my:"+uuid;
    }
}

2. 实体中添加改id生成器

  • 给id添加如**解,strategy 指向我们的id生成器

@GenericGenerator(name = “myGenerator”, strategy = “com.example.springboot.mysqldemo.util.MyIdGenerator”)
@GeneratedValue(generator = “myGenerator”)

@Entity
@Table(name = "User_Info")
public class UserInfo {

    private String id;

    private String name;

   //....


    @JsonProperty
    @Id
    @GenericGenerator(name = "myGenerator", strategy = "com.example.springboot.mysqldemo.util.MyIdGenerator")
    @GeneratedValue(generator = "myGenerator")
    @Column(name = "ID", unique = true, nullable = false, length = 36)
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @JsonProperty
    @Column(name = "name",  length = 136)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

       //....

}

3. 测试

@RestController
@RequestMapping("/index")
@ImportResource(locations = { "classpath:druid-bean.xml" })
public class IndexController {
    @Autowired
    private UserInfoDao userInfoDao;

    @RequestMapping("/addUserInfo")
    public UserInfo getIndex(String name) {
        UserInfo userInfo=new UserInfo();
        userInfo.setName(name);
        userInfoDao.save(userInfo);
        return userInfo;
    }
}

自定义主键生成器

  • success