Spring Boot—17MongoDB
在MongoDB中插入如下的数据
db.baike.insert(
{
_id: 'freemark',
desc: '新一代模板语言',
tag: [
'IT',
'模板语言'
],
comment: {
good: 56,
bad: 1
}
}
) db.baike.insert(
{
_id: 'springboot',
desc: '快速分布式开发框架',
tag: [
'IT',
'spring'
],
comment: {
good: 1256,
bad: 12
}
}
)
pom.xml
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
application.properties
#
server.address=0.0.0.0
server.port=8080
server.servlet.context-path=/test
server.session.timeout=300
server.error.path=/error
#
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.buffered=true
server.tomcat.accesslog.directory=D:/Project/JavaWeb/SpringBoot/04JPASpringBoot/logs
#
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=Asia/Shanghai
#
spring.thymeleaf.cache=true
spring.thymeleaf.enabled=true file.upload.path=D:/Project/JavaWeb/SpringBoot/04JPASpringBoot/fileUpLoad spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=0
spring.servlet.multipart.location=D:/Project/JavaWeb/SpringBoot/04JPASpringBoot/temp
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
spring.servlet.multipart.resolve-lazily=false spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.one.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.druid.one.username=root
spring.datasource.druid.one.password=gis
spring.datasource.druid.one.driver-class-name=com.mysql.cj.jdbc.Driver ##Druid
spring.datasource.druid.one.initial-size=2
spring.datasource.druid.one.max-active=5
spring.datasource.druid.one.min-idle=1
spring.datasource.druid.one.max-wait=60000
spring.datasource.druid.one.pool-prepared-statements=true
spring.datasource.druid.one.max-pool-prepared-statement-per-connection-size=20
spring.datasource.druid.one.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.one.validation-query-timeout=60000
spring.datasource.druid.one.test-on-borrow=false
spring.datasource.druid.one.test-on-return=false
spring.datasource.druid.one.test-while-idle=true
spring.datasource.druid.one.time-between-eviction-runs-millis=60000
spring.datasource.druid.one.min-evictable-idle-time-millis=100000
#spring.datasource.druid.one.max-evictable-idle-time-millis=
spring.datasource.druid.one.filters=stat,wall,log
spring.datasource.druid.one.logSlowSql=true spring.data.mongodb.uri=mongodb://zyx:gis@127.0.0.1:27017/geodb
logging.level.org.springframework.data=debug
启动类
package com.smartmap.sample.test; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement; import com.smartmap.sample.test.conf.DataSourceConfiguration; @EnableTransactionManagement
@SpringBootApplication
public class TestMongoDBApplication { public static void main(String[] args) {
SpringApplication.run(TestMongoDBApplication.class, args); }
}
实体类Baike
package com.smartmap.sample.test.entity; import java.util.ArrayList;
import java.util.Date;
import java.util.List; public class Baike { private String id;
private String desc;
private List<String> tag = new ArrayList<String>();
private Comment comment = null;
private Date createDate = null;
private Date updateDate = null; public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public List<String> getTag() {
return tag;
}
public void setTag(List<String> tag) {
this.tag = tag;
}
public Comment getComment() {
return comment;
}
public void setComment(Comment comment) {
this.comment = comment;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getUpdateDate() {
return updateDate;
} public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
} }
实体类Comment
package com.smartmap.sample.test.entity; import java.util.ArrayList;
import java.util.Date;
import java.util.List; public class Baike { private String id;
private String desc;
private List<String> tag = new ArrayList<String>();
private Comment comment = null;
private Date createDate = null;
private Date updateDate = null; public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getDesc() {
return desc;
} public void setDesc(String desc) {
this.desc = desc;
} public List<String> getTag() {
return tag;
} public void setTag(List<String> tag) {
this.tag = tag;
} public Comment getComment() {
return comment;
} public void setComment(Comment comment) {
this.comment = comment;
} public Date getCreateDate() {
return createDate;
} public void setCreateDate(Date createDate) {
this.createDate = createDate;
} public Date getUpdateDate() {
return updateDate;
} public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
} }
DAO类(强大的MongoTemplate)
package com.smartmap.sample.test.dao.impl; import java.util.Date;
import java.util.List; import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.mongodb.core.DbCallback;
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.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository; import com.mongodb.MongoException;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.smartmap.sample.test.dao.BaikeDao;
import com.smartmap.sample.test.entity.Baike; @Repository
public class BaikeDaoImpl implements BaikeDao {
private final String collectionName = "baike"; @Autowired
MongoTemplate mongoTemplate;
// 插入
public void insertBaike(Baike baike) {
baike.setCreateDate(new Date());
mongoTemplate.insert(baike, collectionName);
}
// 查找所有
public List<Baike> findAllBaike() {
return mongoTemplate.findAll(Baike.class);
}
// 按ID查询
public Baike findBaikeById(String id) {
return mongoTemplate.findById(id, Baike.class);
}
// 按嵌套属性查询
public List<Baike> queryBad(int bad) {
Criteria criteria = Criteria.where("comment.bad").gt(bad);
Query query = Query.query(criteria);
return mongoTemplate.find(query, Baike.class);
}
// 多条件查询
public List<Baike> queryBadAndGood(int bad, int good) {
Criteria criteriaBad = Criteria.where("comment.bad").gt(bad);
Criteria criteriaGood = Criteria.where("comment.good").lt(good);
criteriaBad.andOperator(criteriaGood);
Query query = Query.query(criteriaBad);
return mongoTemplate.find(query, Baike.class);
}
// 更新--原子操作
public Long addCommentGoodCount(String tag) {
Criteria criteria = Criteria.where("tag").in(tag);
Query query = Query.query(criteria);
Update update = new Update();
update.inc("comment.good", 1);
UpdateResult updateResult = mongoTemplate.updateMulti(query, update, Baike.class);
return updateResult.getModifiedCount();
}
// 分页查询
public List<Baike> findBaikeWithPager(String tag, long pageNum) {
Criteria criteria = Criteria.where("tag").in(tag);
Query query = Query.query(criteria);
// 查询总数
long totalCount = mongoTemplate.count(query, Baike.class);
int numOfPage = 10;
long totalPage = totalCount / numOfPage;
if (totalCount % numOfPage != 0) {
totalPage++;
}
if (pageNum > totalPage) {
pageNum = totalPage;
}
// 取出分页的数据
long skip = (pageNum - 1) * numOfPage;
query.skip(skip).limit(numOfPage);
return mongoTemplate.find(query, Baike.class);
} public long updateBaike(Baike baike) {
baike.setUpdateDate(new Date());
Criteria criteria = Criteria.where("_id").is(baike.getId());
Query query = Query.query(criteria);
// 多字段更新
Update update = new Update().set("createDate", baike.getCreateDate()).set("desc", baike.getDesc());
UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Baike.class, collectionName);
return updateResult.getModifiedCount();
}
// 删除
public long deleteBaike(String id) {
Baike baike = new Baike();
baike.setId(id);
DeleteResult deleteResult = mongoTemplate.remove(baike, collectionName);
return deleteResult.getDeletedCount();
}
// 通过调用Mongodb原生的API查询
public Baike findBaikeByIdWithNative(String id) {
final String objectId = id;
Baike baike = mongoTemplate.execute(new DbCallback<Baike>() {
@Override
public Baike doInDB(MongoDatabase mongoDatabase) throws MongoException, DataAccessException {
MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName);
Document document = new Document("_id", objectId);
MongoCursor<Document> cursor = collection.find(document).iterator();
try {
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
}
return null;
} });
return baike;
} }
Service类
package com.smartmap.sample.test.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.smartmap.sample.test.dao.BaikeDao;
import com.smartmap.sample.test.entity.Baike;
import com.smartmap.sample.test.service.BaikeService; @Service
public class BaikeServiceImpl implements BaikeService {
@Autowired
BaikeDao baikeDao; public List<Baike> findAllBaike() {
return baikeDao.findAllBaike();
} public Baike findBaikeById(String id) {
return baikeDao.findBaikeById(id); } public List<Baike> findBaikeWithPager(String tag, long pageNum) {
return baikeDao.findBaikeWithPager(tag, pageNum);
} public Baike insertBaike(Baike baike) {
baikeDao.insertBaike(baike);
return baike;
} public long updateBaike(Baike baike) {
return baikeDao.updateBaike(baike);
} public long deleteBaike(String id) {
return baikeDao.deleteBaike(id);
}
}
Controller类
package com.smartmap.sample.test.controller.rest; import java.util.List; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import com.smartmap.sample.test.entity.Baike;
import com.smartmap.sample.test.service.BaikeService; @RestController
@RequestMapping("/api/v1.1/system/baike")
public class BaikeRestController {
private final Log logger = LogFactory.getLog(BaikeRestController.class);
@Autowired
private BaikeService baikeService; /**
* 查询所有用户
*
* curl -XGET 'http://127.0.0.1:8080/test/api/v1.1/system/baike/'
*
* @return
*/
@GetMapping("/")
public List<Baike> getAllBaikes() {
return baikeService.findAllBaike();
} /**
* 根据Id查询用户
*
* curl -XGET 'http://127.0.0.1:8080/test/api/v1.1/system/baike/springboot'
*
* @param baikeId
* @return
*/
@GetMapping("/{baikeId}")
public Baike getBaikeById(@PathVariable("baikeId") String baikeId) {
return baikeService.findBaikeById(baikeId);
} /**
* 翻页查询用户
*
* curl -XGET 'http://127.0.0.1:8080/test/api/v1.1/system/baike/query?pageNum=1&tag=spring'
*
* @param offset
* @param limit
* @param sortBy
* @param sortOrder
* @return
*/
@GetMapping("/query")
public List<Baike> queryBaikeById(@RequestParam("tag") String tag, @RequestParam("pageNum") long pageNum) {
logger.info(String.valueOf(tag));
logger.info(String.valueOf(pageNum));
return baikeService.findBaikeWithPager(tag, pageNum);
} /**
* 添加用户
*
* curl -XPOST 'http://127.0.0.1:8080/test/api/v1.1/system/baike/' -H'Content-type:application/json;charset=UTF-8' -d '
{
"id": "hadoop",
"desc": "bigdata framework",
"tag": [
"IT",
"bigdta"
],
"comment": {
"good": 3254,
"bad": 25
}
}'
*
* @param baike
* @return
*/
@PostMapping("/")
public int addBaike(@RequestBody Baike baike) {
System.out.println(baike.getId());
baikeService.insertBaike(baike);
return 1;
} /**
* 更新用户
*
* curl -XPUT 'http://127.0.0.1:8080/api/v1.1/system/baike/'
* -H'Content-type:application/json;charset=UTF-8' -d ' { "id": "123",
* "name":"123" } '
*
* @param baike
* @return
*/
@PutMapping("/")
public long updateUse(@RequestBody Baike baike) {
return baikeService.updateBaike(baike);
} /**
* 删除用户
*
* curl -XDELETE 'http://127.0.0.1:8080/api/v1.1/system/baike/123'
*
* @param baikeId
* @return
*/
@DeleteMapping("/{baikeId}")
public String deleteBaike(@PathVariable("baikeId") String baikeId) {
if (baikeService.deleteBaike(baikeId) > 0) {
return "{success:true, message:'delete success'}";
} else {
return "{success:false, message:'delete fail'}";
}
} }
Spring Boot—17MongoDB的更多相关文章
- 玩转spring boot——快速开始
开发环境: IED环境:Eclipse JDK版本:1.8 maven版本:3.3.9 一.创建一个spring boot的mcv web应用程序 打开Eclipse,新建Maven项目 选择quic ...
- 【微框架】之一:从零开始,轻松搞定SpringCloud微框架系列--开山篇(spring boot 小demo)
Spring顶级框架有众多,那么接下的篇幅,我将重点讲解SpringCloud微框架的实现 Spring 顶级项目,包含众多,我们重点学习一下,SpringCloud项目以及SpringBoot项目 ...
- 玩转spring boot——开篇
很久没写博客了,而这一转眼就是7年.这段时间并不是我没学习东西,而是园友们的技术提高的非常快,这反而让我不知道该写些什么.我做程序已经有十几年之久了,可以说是彻彻底底的“程序老炮”,至于技术怎么样?我 ...
- 玩转spring boot——结合redis
一.准备工作 下载redis的windows版zip包:https://github.com/MSOpenTech/redis/releases 运行redis-server.exe程序 出现黑色窗口 ...
- 玩转spring boot——AOP与表单验证
AOP在大多数的情况下的应用场景是:日志和验证.至于AOP的理论知识我就不做赘述.而AOP的通知类型有好几种,今天的例子我只选一个有代表意义的“环绕通知”来演示. 一.AOP入门 修改“pom.xml ...
- 玩转spring boot——结合JPA入门
参考官方例子:https://spring.io/guides/gs/accessing-data-jpa/ 接着上篇内容 一.小试牛刀 创建maven项目后,修改pom.xml文件 <proj ...
- 玩转spring boot——结合JPA事务
接着上篇 一.准备工作 修改pom.xml文件 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q ...
- 玩转spring boot——结合AngularJs和JDBC
参考官方例子:http://spring.io/guides/gs/relational-data-access/ 一.项目准备 在建立mysql数据库后新建表“t_order” ; -- ----- ...
- 玩转spring boot——结合jQuery和AngularJs
在上篇的基础上 准备工作: 修改pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q ...
随机推荐
- 深度学习笔记(六)VGG14
Very Deep Convolutional Networks for Large-Scale Image Recognition 1. 主要贡献 本文探究了参数总数基本不变的情况下,CNN随着层数 ...
- iOS多线程---NSOperation介绍和使用
1. NSOperation实现多线程编程,需要和NSOperationQueue一起使用. (1)先将要执行的操作封装到NSOperation中 (2)将NSOperation对象添加到NSOpe ...
- 在阿里云服务器中安装配置mysql数据库完整教程
阿里云ECS服务器CentOS7上安装MySql服务 (可选)1.确保服务器系统处于最新状态 [root@localhost ~]# yum -y update如果显示以下内容说明已经更新完成 Rep ...
- DIV居中的几种方法
1. body{ text-align:center; } 缺点:body内所有内容一并居中 2. .center{ position: fixed; left: 50%; } 缺点:需要设置posi ...
- java基本语法二
1 运算符 1.1 运算符的概念 运算符是一种特殊的符号,用以表示数据的运算.赋值和比较等. 在java语言中,运算符有如下的分类: ①算术运算符. ②赋值运算符. ③比较运算符(关系运算符). ④逻 ...
- 使用Maven命令行快速创建项目骨架(archetype)
> mvn archetype:generate 接下来就会输出一些列带索引变化的archetype项可供我们选择,然后提示我们选择一个编号,可以直接回车选择默认的编号(392),然后就跟着 ...
- phpredisadmin 莫名其妙错误,打开了无法显示任何数据
一直用的好好的,某天突然只有页面基本框架,redis数据看不到了. 查日志嘛... PHP Fatal error: Allowed memory size of 134217728 bytes e ...
- 【树】Kth Smallest Element in a BST(递归)
题目: Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. ...
- Android 开发工具类 04_KeyBoardUtils
打开或关闭软键盘: 1.打卡软键盘: 2.关闭软键盘. import android.content.Context; import android.view.inputmethod.InputMet ...
- 11-hdfs-NameNode-HA-wtihQJM解决单点故障问题
在hdfs中, NN只有一个, 但其中保存的数据尤其重要, 所以需要将元数据保存, 其中源数据有2个形式, fsimage 和 edit文件, 最简单的解决方法就是复制fsimage, 并在文件修改时 ...