这篇文章给大家介绍spring-data-MongoDB使用mongoTemplate操作mongoDb时@Indexed注解无效且没有自动创建索引该怎么办,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
创新互联于2013年创立,先为索县等服务建站,索县等地企业,进行企业商务咨询服务。为索县企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。
先上代码 ,下面的 “异常” 代码是否会自动创建索引呢?
//订单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可以找到创建索引相关类以及方法的调用路径:

这个是方法签名:
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注解无效且没有自动创建索引该怎么办就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。