在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'}"; } } }