溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

spring-data-mongodb使用mongoTemplate操作mongoDb時(shí)@Indexed注解無效且沒有自動(dòng)創(chuàng)建索引該怎么辦

發(fā)布時(shí)間:2021-09-29 09:20:29 來源:億速云 閱讀:858 作者:柒染 欄目:大數(shù)據(jù)

這篇文章給大家介紹spring-data-mongodb使用mongoTemplate操作mongoDb時(shí)@Indexed注解無效且沒有自動(dòng)創(chuàng)建索引該怎么辦,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。

先上代碼 ,下面的 “異?!?代碼是否會(huì)自動(dòng)創(chuàng)建索引呢?

//訂單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);

答案是 :會(huì)的!

那為什么說是異常代碼呢,因?yàn)樗鼪]有達(dá)到我的預(yù)期,這段代碼會(huì)有兩個(gè)問題:

    1、會(huì)在mongodb里邊創(chuàng)建兩個(gè) collection : order_ 和 order_${month}

    2、索引會(huì)創(chuàng)建在 “order_” 這個(gè)collection里邊,而不會(huì)在 “order_${month}”

這個(gè)時(shí)候答案就很明顯了:自動(dòng)創(chuàng)建索引的時(shí)候 ,讀取的collectionName 是 @Document注解里邊的值,而不是 insert的時(shí)候傳入的值。

結(jié)論已經(jīng)有了,就該看看它是怎么把傳入的 collectionName弄丟的了

    通過debug可以找到創(chuàng)建索引相關(guān)類以及方法的調(diào)用路徑:

spring-data-mongodb使用mongoTemplate操作mongoDb時(shí)@Indexed注解無效且沒有自動(dòng)創(chuàng)建索引該怎么辦

這個(gè)是方法簽名:

checkForIndexes((MongoPersistentEntity<?>) entity);

最終只剩下了entity。通過entity的@Document注解來獲取collectionName。細(xì)節(jié)就不貼圖了,建議去debug下看看源碼。

原因找到了,最終要如何解決當(dāng)前的問題呢?上代碼:

        //字段索引
        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注解去掉。

關(guān)于spring-data-mongodb使用mongoTemplate操作mongoDb時(shí)@Indexed注解無效且沒有自動(dòng)創(chuàng)建索引該怎么辦就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI