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 ...
随机推荐
- 【ARC072F】 Dam 单调队列
题目大意: 有一个水库,容量为$L$,一开始是空的.有$n$天. 对于第i天,每天早上有$v_i$单位的,水温为$t_i$的水流进来.每天晚上你可以放掉一些水,多少自定.但是必须保证第二天水库不会溢出 ...
- vsto之一简介(系列文章为转载)
该系列文章转载自 http://bbs.51cto.com/thread-1017338-1.html 参考资料 http://www.excelpx.com/thread-184209-1-1 ...
- 递归、字节流、文件复制_DAY20
1:递归(理解) (1)方法定义中调用方法本身的现象. (2)递归注意事项: A:要有出口,否则就是死递归. B:次数不能太多,否则内存溢出. 特殊事项:构造方法不能递归定义. 例子:cn.itcas ...
- 【Tomcat】使用记录
同时绑定ipv4和ipv6 <Connector port="8080" protocol="HTTP/1.1" connectionTimeout=&q ...
- sublime text ubuntu
{ "color_scheme": "Packages/User/SublimeLinter/Dawn (SL).tmTheme", "font_fa ...
- python strip()函数的用法
函数原型 声明:s为字符串,rm为要删除的字符序列 s.strip(rm) 删除s字符串中开头.结尾处,位于 rm删除序列的字符 s.lstrip(rm) 删除s字符串中 ...
- 拦截并记录数据库操作-Logging and Intercepting Database Operations
原文:http://msdn.microsoft.com/zh-cn/data/dn469464 Logging and Intercepting Database Operations Starti ...
- solr 7.6 安装部署与遇到的问题
目录 安装 solr 配置solr 到tomcat(关键) 配置依赖包 创建tomcat solr 的 classes 文件 创建 solr 的core 的主目录(也就是存放core的位置) 修改配置 ...
- centos6.5 + 7 静态ip配置
2017/09/19日更, centos6.5 可用 DEVICE=eth0 TYPE=Ethernet ONBOOT=yes NM_CONTROLLED=yes BOOTPROTO=static D ...
- springboot-5-整合jpa
######## ##springboot-parent.version: ## jdk 1.8 ## ####### 在整合jpa之前, 先说下mysql 步骤: 1), 在application. ...