Max*_*xim 9 java spring mongodb spring-data-mongodb
要为集合创建索引(如https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/所述),可以使用以下内容:
mongoTemplate.indexOps(Person.class).ensureIndex(new Index().on("name",Order.ASCENDING));
Run Code Online (Sandbox Code Playgroud)
但是我应该在程序的哪个位置放置此代码段?
在相关的存储库的构造函数中?我现在已经这样做了它并且它可以工作,但我不知何故觉得这是糟糕的设计.
在Mongo配置的某个地方?我还没有找到一个合适的方法来覆盖这里https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/config/AbstractMongoConfiguration.html
Daw*_*zke 13
如果你需要以编程方式完成,你可以创建新的Spring @Configuration并执行这样的初始化:
@Configuration
@DependsOn("mongoTemplate")
public class CollectionsConfig {
@Autowired
private MongoTemplate mongoTemplate;
@PostConstruct
public void initIndexes() {
mongoTemplate.indexOps("collectionName") // collection name string or .class
.ensureIndex(
new Index().on("name", Sort.Direction.ASC)
);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2791 次 |
最近记录: |