栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot Mongodb重新封装自增ID(数值)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot Mongodb重新封装自增ID(数值)

目的是还原JpaRepository中的自增ID设置

1、自定义注解:@GeneratedValue

2、定义枚举GenerationType, 用于选择ID赋值的类型(本文章并未真正使用,可作为拓展功能)

3、重写监听事件里面的方法,而进行某些处理,该类需要继承AbstractMongoEventListener类,

注意这里定义的集合中Id默认都是数值类型, 如果需要使用ObjectId则需要过滤集合。

@Slf4j
@Configuration
@RequiredArgsConstructor
public class NosqlIdConfig extends AbstractMongoEventListener {

    private final MongoTemplate mongoTemplate;

    @PostConstruct
    public void init(){
        log.info("文档型数据库开始初始化所有集合Id......");
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Set collectionNames = mongoTemplate.getCollectionNames();
                for (String collectionName : collectionNames) {
                    long count = mongoTemplate.count(new Query(), collectionName);
                    Long id = 0L;
                    if (count > 0){
                        List maps = mongoTemplate.findAll(Map.class, collectionName);
                        for (Map map : maps) {
                            Long src = (Long) map.get("_id");
                            if (src.longValue() > id.longValue()){
                                id = src;
                            }
                        }
                    }
                    identity.put(collectionName, id);
                }
                log.info("文档型数据库所有集合Id初始化成功: {}", identity);
            }
        });
        thread.setName("document");
        thread.start();
    }

    @PreDestroy
    public synchronized void destory(){
        identity.clear();
    }

    private static Map identity = new linkedHashMap<>();

    @Override
    public synchronized void onBeforeConvert(BeforeConvertEvent event) {
        Object source = event.getSource();
        Class sourceClass = source.getClass();
        if (!sourceClass.isAnnotation()){
            super.onBeforeConvert(event);
        }
        document document = sourceClass.getAnnotation(document.class);
        if (null != source) {
            ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {
                @Override
                public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                    ReflectionUtils.makeAccessible(field);
                    if (field.isAnnotationPresent(GeneratedValue.class)) {
                        Object value = field.get(source);
                        if (value == null) {
                            field.set(source, getAutoId(document.collection()));
                        }else {
                            field.set(source, value);
                        }
                    }
                }
            });
        }
    }

    private Long getAutoId(String collectionName){
        Long id = 0L;
        boolean exist = identity.containsKey(collectionName);
        if (exist){
            id = identity.get(collectionName) + 1L;
        }else {
            id = 1L;
        }
        identity.put(collectionName, id);
        return id;
    }

} 
4、自定义注解:@EnableMongodb
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@documented
@Inherited
@import({NosqlIdConfig.class})
public @interface EnableMongodb {

}

5、在工程中应用只需使用注解@EnableMongodb便可将自定义配置生效,注意需要在文档对象的Id字段上加上@GeneratedValue方可生效

@EnableMongodb
@EnableMinio
@SpringBootApplication
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

}
转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号