百度UidGenerator在Springboot中的应用

1、在springboot中的基本运用

  • 导入maven依赖

<!--百度UidGenerator-->
<!-- https://mvnrepository.com/artifact/com.chungkui/uid-generator-spring-boot-starter -->
 <dependency>
   <groupId>com.chungkui</groupId>
   <artifactId>uid-generator-spring-boot-starter</artifactId>
   <version>1.4-bate</version>
 </dependency>
  • 编写service实现类

@Service
public class WorkerNodeEntityServiceImpl implements WorkerNodeEntityService {

   @Override
   public Long save(WorkerNodeEntity workerNodeEntity) {
       //可将workerNodeEntity对象添加到数据库
       return 1L;
   }
   
}
  • 测试是否能生成id

@RestController
public class TestController {

   @Resource
   private UidGenerator uidGenerator;
 
   @GetMapping("/test")
   public String test() {
       long uid = uidGenerator.getUID();
       return uidGenerator.parseUID(uid);
   }
}

2、在mybatis-plus中整合UidGenerator,配置id自定义生成策略

  • 创建CustomIdGenerator类实现IdentifierGenerator接口

@Component
public class CustomIdGenerator implements IdentifierGenerator {

   @Resource
   private UidGenerator uidGenerator;

   @Override
   public Number nextId(Object entity) {
       // 自定义ID生成逻辑,例如使用UUID生成ID
       return uidGenerator.getUID();
   }
}
  • 在配置类中添加如下配置,添加自定义id生成器到mybatis-plus的全局配置中

@Configuration
public class MpConfig {

   @Resource
   private CustomIdGenerator customIdGenerator;

   @Bean
   public GlobalConfig globalConfig() {
       GlobalConfig globalConfig = new GlobalConfig();
       globalConfig.setMetaObjectHandler(new MyMetaObjectHandler()); // 设置自动填充策略
       globalConfig.setIdentifierGenerator(customIdGenerator);// 设置自定义ID生成器
       return globalConfig;
   }

}
  • 在实体类中的id属性上添加TableId注解

@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel(value="StudentInfo对象", description="")
public class StudentInfo extends BaseEntity {

   private static final long serialVersionUID = 1L;

   @ApiModelProperty(value = "student_id")
   @TableId(value = "student_id", type = IdType.NONE)
   private Long studentId;

   @ApiModelProperty(value = "年龄")
   private Integer age;

   @ApiModelProperty(value = "姓名")
   private String name;

}

 

转自:https://www.cnblogs.com/lbao/p/17646205.html