spring-data-mongodb使用mongoTemplate操作mongoDb时@Indexed注解无效且没有自动创建索引该怎么办

发布时间:2021-09-29 09:20:29 作者:柒染
来源:亿速云 阅读:705

这篇文章给大家介绍spring-data-mongodb使用mongoTemplate操作mongoDb时@Indexed注解无效且没有自动创建索引该怎么办,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

先上代码 ,下面的 “异常” 代码是否会自动创建索引呢?

//订单doc
@Data
@Accessors(chain = true)
@FieldNameConstants
@Document(collection = "order_")
public class Order implements Serializable {

    @Id
    private String id;
    @Indexed
    private String tid;
    @Indexed
    private String tradeId;
    private String status;
    private String created;

}

//使用mongoTemplate做插入操作,按照月份分表

mongoTemplate.insert(orderRecord, mongoTemplate.getCollectionName(Order.class) + month);

答案是 :会的!

那为什么说是异常代码呢,因为它没有达到我的预期,这段代码会有两个问题:

    1、会在mongodb里边创建两个 collection : order_ 和 order_${month}

    2、索引会创建在 “order_” 这个collection里边,而不会在 “order_${month}”

这个时候答案就很明显了:自动创建索引的时候 ,读取的collectionName 是 @Document注解里边的值,而不是 insert的时候传入的值。

结论已经有了,就该看看它是怎么把传入的 collectionName弄丢的了

    通过debug可以找到创建索引相关类以及方法的调用路径:

spring-data-mongodb使用mongoTemplate操作mongoDb时@Indexed注解无效且没有自动创建索引该怎么办

这个是方法签名:

checkForIndexes((MongoPersistentEntity<?>) entity);

最终只剩下了entity。通过entity的@Document注解来获取collectionName。细节就不贴图了,建议去debug下看看源码。

原因找到了,最终要如何解决当前的问题呢?上代码:

        //字段索引
        IndexOperations indexOps2 = mongoTemplate.indexOps(orderCollectionName);
        String[] indexFields2 = Arrays.stream(Order.class.getDeclaredFields())
                .filter(f -> f.isAnnotationPresent(Indexed.class))
                .map(Field::getName)
                .toArray(String[]::new);
        for (String indexField : indexFields2) {
            if (StringUtils.hasText(indexField)) {
                indexOps2.ensureIndex(new Index(indexField, Sort.Direction.ASC));
            }
        }

至此,问题解决。

最后别忘了把@Document注解去掉。

关于spring-data-mongodb使用mongoTemplate操作mongoDb时@Indexed注解无效且没有自动创建索引该怎么办就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. mongodb 索引日常维护操作
  2. mongodb索引

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

mongodb @indexed spring data

上一篇:如何解决asp.net中“从客户端中检测到有潜在危险的Request.Form值”错误

下一篇:如何解决composer错误使用引发的问题

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》