还是那一套:
加spring data mongoDB 的dependencies 在Pom.xml里面。
然后config mongoDB by add the configration class:
@Configuration
public class AppConfig {
public @Bean MongoClient mongoClient() {
return MongoClients.create('mongodb://localhost:27017');
}
}
-
what’s mongoDBTemplate class:
it provide conveniene operations to create, update, delete and read mongoDB database
also it can mapping domain objects and mongoDB documents.
the exception handling mechanism is very implemented(originally from mongoDB driver.) -
ways to initialize mongoDBTemplate class?
MongoTemplate(MongoClient mongoClient, String databaseName) - Takes MongoClient object and default database name.
MongoTemplate(MongoDatabaseFactory mongoFactory) - Takes a MongoDataBaseFactory object that encapsulates MongoClient, database, and its credentials. -
CRUD operation
MongoTemplate mongoTemplate = new MongoTemplate(MongoClients.create(), 'database');
//Create MongoDB document
Website w = new Website('interviewgrid','www.interviewgrid.com');
mongoTemplate.insert(w);
//find document
w = findById('interviewgrid',Website.class);
//update document
mongoTemplate.updateFirst(query(where('id')is('interviewgrid')),update('url','http://www.interviewgrid.com'), Website.class);
//delete document
mongoTemplate.remove(w);
看到了吗 很容易使用。所以不用太慌。

本文介绍了如何在项目中集成Spring Data MongoDB,并演示了基本的CRUD操作。通过配置MongoClient连接本地MongoDB实例,利用MongoDBTemplate进行文档的创建、读取、更新和删除。
4288

被折叠的 条评论
为什么被折叠?



