展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

自定义id生成器

  • 实体类
@Data
public class User {
    @TableId(type = IdType.ASSIGN_ID)
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
  • mapper
@Mapper
public interface UserMapper extends BaseMapper<User> {

}
  • service
@Service
public class UserService extends ServiceImpl<UserMapper, User> {

}
  • id生成器
@Slf4j
@Component
public class CustomIdGenerator implements IdentifierGenerator {

    private final AtomicLong al = new AtomicLong(1);

    @Override
    public Long nextId(Object entity) {
        //可以将当前传入的class全类名来作为bizKey,或者提取参数来生成bizKey进行分布式Id调用生成.
        String bizKey = entity.getClass().getName();
        log.info("bizKey:{}", bizKey);
        MetaObject metaObject = SystemMetaObject.forObject(entity);
        String name = (String) metaObject.getValue("name");
        final long id = al.getAndAdd(1);
        log.info("为{}生成主键值->:{}", name, id);
        return id;
    }
}
  • 测试类
@Test
public void test() {
    User user = new User();
    user.setName("靓仔");
    user.setAge(18);
    userMapper.insert(user);
    Assertions.assertEquals(Long.valueOf(1L), user.getId());
}

# 控制台
为靓仔生成主键值->:1
posted @ 2022-07-19 16:54  DogLeftover  阅读(105)  评论(0编辑  收藏  举报