上篇介绍Spring Boot 连接Redis,本章开始介绍使用MongoDB, 在Spring Boot中使用MongoDB一样的简单与高效,下文开始演示。(坑以挖深,放心跳)
访问MongoDB
- 引入依赖(POM)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
- 启动本地MongoDB
1 . 官网下载最新社区版URL,:
https://www.mongodb.com/download-center?jmp=nav
请根据自身的系统环境下载,如下图:
安装后启动服务如下:
Spring Boot的默认配置,application.properties配置参数:
** Mongo 3.0版以下**的配置
spring.data.mongodb.host=mongoserver
spring.data.mongodb.port=27017
** Mongo 3.0版以上**的配置
spring.data.mongodb.uri=mongodb://use:pwd@localhost:27017/test
我本机的配置如下(供参考MongoDB 3.2):
spring.data.mongodb.uri=mongodb://test01:test01@localhost:27017/test```
###创建数据实体
package com.vo;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = -3258839839160856613L;
private Long id;
private String userName;
private String moblie;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getMoblie() {
return moblie;
}
public void setMoblie(String moblie) {
this.moblie = moblie;
}
}
###编写单元测试用例:
import com.Application;
import com.vo.User;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.Instant;
/**
- Description: mongoDB 使用
- author: 慢慢来了
- date: 2017/3/20 17:17
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class MongoDBTest {
@Autowired
private MongoTemplate mongoTemplate;
@Test
public void saveUser(){
User user = new User();
user.setId(Instant.now().toEpochMilli());
user.setUserName("王大锤");
user.setMobile("13300000000");
mongoTemplate.save(user);
Assert.assertTrue(mongoTemplate.findAll(User.class).size() == 1);
}
@Test
public void findUser(){
User user = mongoTemplate.findOne(new Query(Criteria.where("userName").is("王大锤")) , User.class);
Assert.assertEquals("13300000000" , user.getMobile());
}
}
###查看结果
通过Mongo命令直接登录并授权如下:
![Paste_Image.png](http://upload-images.jianshu.io/upload_images/5224684-0780b80f6c278f48.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
执行查询命令:
![Paste_Image.png](http://upload-images.jianshu.io/upload_images/5224684-31fb9e04bc914b69.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
###参考资料:
> http://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/htmlsingle/