Spring Boot 揭秘与实战(二) 数据存储篇 - MongoDB
文章目录
本文讲解Spring Boot基础下,如何使用MongoDB,编写数据访问。
环境依赖
修改 POM 文件,添加spring-boot-starter-data-mongodb依赖。
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-mongodb</artifactId>
- </dependency>
数据源
方案一 使用 Spring Boot 默认配置
MongoDB 使用,在 Spring Boot 中同样提供了自配置功能。
默认使用localhost:27017的名称叫做test的数据库。
此外,我们也可以在 src/main/resources/application.properties 中配置数据源信息。
- spring.data.mongodb.uri=mongodb://localhost:27017/springboot-db
如果存在密码,配置改成如下
- spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/dbname
方案二 手动创建
通过 Java Config 创建mongoTemplate。
- @Configuration
- @EnableMongoRepositories
- public class MongoConfig extends AbstractMongoConfiguration {
- private String mongoHost = "localhost";
- private int mongoPort = 27017;
- private String dbName = "springboot-db";
- private static final String MONGO_BASE_PACKAGE = "com.lianggzone.springboot.action.data.mongodb.entity";
- @Autowired
- private ApplicationContext appContext;
- @Override
- protected String getDatabaseName() {
- return dbName;
- }
- @Override
- public Mongo mongo() throws Exception {
- MongoClient mongoClient = new MongoClient(mongoHost, mongoPort);
- return mongoClient;
- }
- @Override
- protected String getMappingBasePackage() {
- return MONGO_BASE_PACKAGE;
- }
- @Override
- @Bean
- public MongoTemplate mongoTemplate() throws Exception {
- return new MongoTemplate(mongo(), getDatabaseName());
- }
- }
使用mongoTemplate操作
实体对象
- @Document(collection = "author")
- public class Author {
- @Id
- private Long id;
- private String realName;
- private String nickName;
- // SET和GET方法
- }
DAO相关
我们通过mongoTemplate进行数据访问操作。
- @Repository
- public class AuthorDao {
- @Autowired
- private MongoTemplate mongoTemplate;
- public void add(Author author) {
- this.mongoTemplate.insert(author);
- }
- public void update(Author author) {
- this.mongoTemplate.save(author);
- }
- public void delete(Long id) {
- Query query = new Query();
- query.addCriteria(Criteria.where("_id").is(id));
- this.mongoTemplate.remove(query, Author.class);
- }
- public Author findAuthor(Long id) {
- return this.mongoTemplate.findById(id, Author.class);
- }
- public List<Author> findAuthorList() {
- Query query = new Query();
- return this.mongoTemplate.find(query, Author.class);
- }
- }
Service相关
Service层调用Dao层的方法,这个是典型的套路。
- @Service
- public class AuthorService {
- @Autowired
- private AuthorDao authorDao;
- public void add(Author author) {
- this.authorDao.add(author);
- }
- public void update(Author author) {
- this.authorDao.update(author);
- }
- public void delete(Long id) {
- this.authorDao.delete(id);
- }
- public Author findAuthor(Long id) {
- return this.authorDao.findAuthor(id);
- }
- public List<Author> findAuthorList() {
- return this.authorDao.findAuthorList();
- }
- }
Controller相关
为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。
- @RestController
- @RequestMapping(value="/data/mongodb/author")
- public class AuthorController {
- @Autowired
- private AuthorService authorService;
- /**
- * 查询用户列表
- */
- @RequestMapping(method = RequestMethod.GET)
- public Map<String,Object> getAuthorList(HttpServletRequest request) {
- List<Author> authorList = this.authorService.findAuthorList();
- Map<String,Object> param = new HashMap<String,Object>();
- param.put("total", authorList.size());
- param.put("rows", authorList);
- return param;
- }
- /**
- * 查询用户信息
- */
- @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
- public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
- Author author = this.authorService.findAuthor(userId);
- if(author == null){
- throw new RuntimeException("查询错误");
- }
- return author;
- }
- /**
- * 新增方法
- */
- @RequestMapping(method = RequestMethod.POST)
- public void add(@RequestBody JSONObject jsonObject) {
- String userId = jsonObject.getString("user_id");
- String realName = jsonObject.getString("real_name");
- String nickName = jsonObject.getString("nick_name");
- Author author = new Author();
- if (author!=null) {
- author.setId(Long.valueOf(userId));
- }
- author.setRealName(realName);
- author.setNickName(nickName);
- try{
- this.authorService.add(author);
- }catch(Exception e){
- e.printStackTrace();
- throw new RuntimeException("新增错误");
- }
- }
- /**
- * 更新方法
- */
- @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.PUT)
- public void update(@PathVariable Long userId, @RequestBody JSONObject jsonObject) {
- Author author = this.authorService.findAuthor(userId);
- String realName = jsonObject.getString("real_name");
- String nickName = jsonObject.getString("nick_name");
- author.setRealName(realName);
- author.setNickName(nickName);
- try{
- this.authorService.update(author);
- }catch(Exception e){
- e.printStackTrace();
- throw new RuntimeException("更新错误");
- }
- }
- /**
- * 删除方法
- */
- @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.DELETE)
- public void delete(@PathVariable Long userId) {
- try{
- this.authorService.delete(userId);
- }catch(Exception e){
- throw new RuntimeException("删除错误");
- }
- }
- }
总结
上面这个简单的案例,让我们看到了 Spring Boot 整合 MongoDB 的整个流程。实际上,与 Spring 4 中 通过 Spring Data MongoDB 整合 MongoDB 是相同的, Spring Boot 默认集成了一些配置信息,但是个人更加偏向于方案二的手动创建方式,有更好的扩展性。
源代码
相关示例完整代码: springboot-action
(完)
如果觉得我的文章对你有帮助,请随意打赏。

- 版权声明:本文由 梁桂钊 发表于 梁桂钊的博客
- 转载声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证),非商业转载请注明作者及出处,商业转载请联系作者本人。
- 文章标题:Spring Boot 揭秘与实战(二) 数据存储篇 - MongoDB
- 文章链接:http://blog.720ui.com/2016/springboot_02_data_mongodb/
Spring Boot 揭秘与实战(二) 数据存储篇 - MongoDB的更多相关文章
- Spring Boot 揭秘与实战(二) 数据存储篇 - 声明式事务管理
文章目录 1. 声明式事务 2. Spring Boot默认集成事务 3. 实战演练4. 源代码 3.1. 实体对象 3.2. DAO 相关 3.3. Service 相关 3.4. 测试,测试 本文 ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - ElasticSearch
文章目录 1. 版本须知 2. 环境依赖 3. 数据源 3.1. 方案一 使用 Spring Boot 默认配置 3.2. 方案二 手动创建 4. 业务操作5. 总结 4.1. 实体对象 4.2. D ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - Redis
文章目录 1. 环境依赖 2. 数据源 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 3. 使用 redisTemplate 操作4. 总结 3.1. 工具类 ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - JPA整合
文章目录 1. 环境依赖 2. 数据源 3. 脚本初始化 4. JPA 整合方案一 通过继承 JpaRepository 接口 4.1. 实体对象 4.2. DAO相关 4.3. Service相关 ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - MyBatis整合
文章目录 1. 环境依赖 2. 数据源3. 脚本初始化 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 4. MyBatis整合5. 总结 4.1. 方案一 通过 ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - 数据访问与多数据源配置
文章目录 1. 环境依赖 2. 数据源 3. 单元测试 4. 源代码 在某些场景下,我们可能会在一个应用中需要依赖和访问多个数据源,例如针对于 MySQL 的分库场景.因此,我们需要配置多个数据源. ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - MySQL
文章目录 1. 环境依赖 2. 数据源3. 脚本初始化 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 4. 使用JdbcTemplate操作5. 总结 4.1. ...
- Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门
文章目录 1. 声明式缓存 2. Spring Boot默认集成CacheManager 3. 默认的 ConcurrenMapCacheManager 4. 实战演练5. 扩展阅读 4.1. Mav ...
- Spring Boot 揭秘与实战(二) 数据缓存篇 - Redis Cache
文章目录 1. Redis Cache 集成 2. 源代码 本文,讲解 Spring Boot 如何集成 Redis Cache,实现缓存. 在阅读「Spring Boot 揭秘与实战(二) 数据缓存 ...
随机推荐
- 使用SetInterval时函数不能传参问题
无论是window.setTimeout还是window.setInterval,在使用函数名作为调用句柄时都不能带参数,而在许多场合必须要带参数,这就需要想方法解决.经网上查询后整理如下:例如对于函 ...
- Linux 下Qt实现守护进程实例(转)
原文地址:Linux守护进程的编程方法(含实例) 作者:lingdxuyan 参考文献 Linux信号列表(zz) Linux 守护进程的编程方法 linux上编写守护进程的例程 Linux下后台守 ...
- Qt之获取子部件
Qt5.10 QList<QObject*> list_children = this->children(); for(int i=0;i<list_children.siz ...
- Struts 2 初步入门(一)
搭建Struts 2环境步骤 下载jar包----->创建web项目---->创建并完善相关配置文件---->创建action并测试启动 下载jar包访问网站:http://stru ...
- ubuntu下唤醒或休眠远程计算机
ubuntu让我明白,没有什么完美的东西,要想完美必须付出代价.要么花时间折腾,要么花时间赚钱买系统. 人生也是一样,所以不要期待什么完美.哪有那么好的人,在合适的时间合适的地点让你遇见,还对你有感觉 ...
- ubuntu启用root登陆
ubuntu系统不能够默认以root用户登陆系统如果你为了方便开发想每次登陆的时候以root用户登陆那么需要手动的做写更改打开终端 首先输入命令 sudo passwd root更新你的密码然后输入 ...
- 蓝桥杯—BASIC-27 2n皇后问题(DFS)
问题描述 给定一个n*n的棋盘,棋盘中有一些位置不能放皇后.现在要向棋盘中放入n个黑皇后和n个白皇后, 使任意的两个黑皇后都不在同一行.同一列或同一条对角线上,任意的两个白皇后都不在同一行. 同一列或 ...
- webpack+typescript
1. npm install --save typescript 2. npm install --save ts-loader webpack.config.js module.exports = ...
- 线性回归决定系数之Why SST=SSE+SSR
线性最小二乘法的原则是使得误差的平方和最小,即 为了使S最小,令其对参数的偏导数为零: 即 即 根据方程1和方程2,得 又∵ ∴ 参考链接:https://math.stackexchange.com ...
- vue数据请求显示loading图
一般项目中,有时候会要求,你在数据请求的时候显示一张gif图片,然后数据加载完后,消失.这个,一般只需要在封装的axios中写入js事件即可.当然,我们首先需要在app.vue中,加入此图片.如下: ...