面试向:SpringData MongoDB

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

还是那一套:
加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');
 }
}
  1. 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.)

  2. 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.

  3. 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);

看到了吗 很容易使用。所以不用太慌。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值