哈爾濱網(wǎng)站制作公司電話南京網(wǎng)絡優(yōu)化培訓
文章目錄
- 項目搭建
- 文章評論實體類的編寫
- 文章評論的基本增刪改查
- 根據(jù)上級ID查詢文章評論的分頁列表
- MongoTemplate實現(xiàn)評論點贊
- GITHUB
項目搭建
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.6.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>itcast</groupId><artifactId>article</artifactId><version>1.0-SNAPSHOT</version><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency></dependencies></project>
(2)創(chuàng)建application.yml
spring:#數(shù)據(jù)源配置data:mongodb:# 主機地址host: 192.168.218.131# 數(shù)據(jù)庫database: articledb# 默認端口是27017port: 27017username: rootpassword: "123456"authentication-database: admin #必須設置設置權限認證的數(shù)據(jù)庫
(3)創(chuàng)建啟動類
onenewcode.article.ArticleApplication
package onenewcode.article;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class ArticleApplication {public static void main(String[] args) {SpringApplication.run(ArticleApplication.class, args);}}
(4)啟動項目,看是否能正常啟動,控制臺沒有錯誤。
文章評論實體類的編寫
創(chuàng)建實體類 創(chuàng)建包onenewcode.article,包下建包po用于存放實體類,創(chuàng)建實體類
onenewcode.article.po.Comment
package onenewcode.article.service;import onenewcode.article.dao.CommentRepository;
import onenewcode.article.po.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
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.Service;import java.util.List;@Service
public class CommentService {@Autowiredprivate CommentRepository commentRepository;@Autowiredprivate MongoTemplate mongoTemplate;/*** 保存一個評論* @param comment*/public void saveComment(Comment comment){//如果需要自定義主鍵,可以在這里指定主鍵;如果不指定主鍵,MongoDB會自動生成主鍵//設置一些默認初始值。。。//調用daocommentRepository.save(comment);}/*** 更新評論* @param comment*/public void updateComment(Comment comment){//調用daocommentRepository.save(comment);}/*** 根據(jù)id刪除評論* @param id*/public void deleteCommentById(String id){//調用daocommentRepository.deleteById(id);}/*** 查詢所有評論* @return*/public List<Comment> findCommentList(){//調用daoreturn commentRepository.findAll();}/*** 根據(jù)id查詢評論* @param id* @return*/public Comment findCommentById(String id){//調用daoreturn commentRepository.findById(id).get();}public Page<Comment> findCommentListByParentid(String parentid,int page,int size) {return commentRepository.findByParentid(parentid,PageRequest.of(page-1,size));}public void updateCommentLikenum(String id){// 查詢條件Query query = Query.query(Criteria.where("_id").is(id));// 更新條件Update update = new Update();update.inc("likenum");mongoTemplate.updateFirst(query,update,Comment.class);}
}
**說明:**索引可以大大提升查詢效率,一般在查詢字段上添加索引,索引的添加可以通過Mongo的命令來添加,也可以在Java的實體類中通過注解添加。
1)單字段索引注解@Indexed
org.springframework.data.mongodb.core.index.Indexed.class
聲明該字段需要索引,建索引可以大大的提高查詢效率。
Mongo命令參考:
db.comment.createIndex({“userid”:1})
2)復合索引注解@CompoundIndex
org.springframework.data.mongodb.core.index.CompoundIndex.class
復合索引的聲明,建復合索引可以有效地提高多字段的查詢效率。
db.comment.createIndex({“userid”:1,“nickname”:-1})
文章評論的基本增刪改查
- 創(chuàng)建數(shù)據(jù)訪問接口 onenewcode.article包下創(chuàng)建dao包,包下創(chuàng)建接口
onenewcode.article.dao.CommentRepository
package onenewcode.article.dao;import onenewcode.article.po.Comment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;//評論的持久層接口
public interface CommentRepository extends MongoRepository<Comment,String> {}
- 創(chuàng)建業(yè)務邏輯類 onenewcode.article包下創(chuàng)建service包,包下創(chuàng)建類
import onenewcode.article.po.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;//評論的業(yè)務層
@Servicepublic class CommentService {//注入dao@Autowiredprivate CommentRepository commentRepository;/*** 保存一個評論* @param comment*/public void saveComment(Comment comment){//如果需要自定義主鍵,可以在這里指定主鍵;如果不指定主鍵,MongoDB會自動生成主鍵//設置一些默認初始值。。。//調用daocommentRepository.save(comment);}/*** 更新評論* @param comment*/public void updateComment(Comment comment){//調用daocommentRepository.save(comment);}/*** 根據(jù)id刪除評論* @param id*/public void deleteCommentById(String id){//調用daocommentRepository.deleteById(id);}/*** 查詢所有評論* @return*/public List<Comment> findCommentList(){//調用daoreturn commentRepository.findAll();}/*** 根據(jù)id查詢評論* @param id* @return*/public Comment findCommentById(String id){//調用daoreturn commentRepository.findById(id).get();}}
- 新建Junit測試類,測試保存和查詢所有:
package onenewcode.article.service;import onenewcode.article.ArticleApplication;
import onenewcode.article.po.Comment;
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.domain.Page;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.LocalDateTime;
import java.util.List;
//測試評論的業(yè)務層
//SpringBoot的Junit集成測試//SpringBoot的測試環(huán)境初始化,參數(shù):啟動類
@SpringBootTest
public class CommentServiceTest {//注入Service@Autowiredprivate CommentService commentService;/*** 保存一個評論*/@Testpublic void testSaveComment(){Comment comment=new Comment();comment.setArticleid("100000");comment.setContent("測試添加的數(shù)據(jù)");comment.setCreatedatetime(LocalDateTime.now());comment.setUserid("1003");comment.setNickname("凱撒大帝");comment.setState("1");comment.setLikenum(0);comment.setReplynum(0);commentService.saveComment(comment);}/*** 查詢所有數(shù)據(jù)*/@Testpublic void testFindAll(){List<Comment> list = commentService.findCommentList();System.out.println(list);}/*** 測試根據(jù)id查詢*/@Testpublic void testFindCommentById(){Comment comment = commentService.findCommentById("5d6a27b81b8d374798cf0b41");System.out.println(comment);}
}
添加結果:
根據(jù)上級ID查詢文章評論的分頁列表
- CommentRepository新增方法定義
//根據(jù)父id,查詢子評論的分頁列表
Page findByParentid(String parentid, Pageable pageable);
- CommentService新增方法
/*** 根據(jù)父id查詢分頁列表* @param parentid* @param page* @param size* @return*/public Page<Comment> findCommentListPageByParentid(String parentid,int page ,int size){return commentRepository.findByParentid(parentid, PageRequest.of(page-1,size));}
- junit測試用例
/*** 測試根據(jù)父id查詢子評論的分頁列表*/@Testpublic void testFindCommentListPageByParentid(){Page<Comment> pageResponse = commentService.findCommentListPageByParentid("3", 1, 2);System.out.println("----總記錄數(shù):"+pageResponse.getTotalElements());System.out.println("----當前頁數(shù)據(jù):"+pageResponse.getContent());}
MongoTemplate實現(xiàn)評論點贊
以下點贊的臨時示例代碼: CommentService 新增updateThumbup方法
/*** 點贊-效率低* @param id*/public void updateCommentThumbupToIncrementingOld(String id){Comment comment = CommentRepository.findById(id).get();comment.setLikenum(comment.getLikenum()+1);CommentRepository.save(comment);}
以上方法雖然實現(xiàn)起來比較簡單,但是執(zhí)行效率并不高,因為我只需要將點贊數(shù)加1就可以了,沒必要查詢出所有字段修改后再更新所有字
段。(蝴蝶效應)
我們可以使用MongoTemplate類來實現(xiàn)對某列的操作。 (1)修改CommentService
//注入MongoTemplate@Autowiredprivate MongoTemplate mongoTemplate;/*** 點贊數(shù)+1* @param id*/public void updateCommentLikenum(String id){//查詢對象
Query query=Query.query(Criteria.where("_id").is(id));//更新對象
Update update=new Update();//局部更新,相當于$set//
update.set(key,value)//遞增$inc//
update.inc("likenum",1);update.inc("likenum");}//參數(shù)1:查詢對象
//參數(shù)2:更新對象
//參數(shù)3:集合的名字或實體類的類型Comment.classmongoTemplate.updateFirst(query,update,"comment");
}
- 測試用例:
/*** 點贊數(shù)+1*/@Testpublic void testUpdateCommentLikenum(){//對3號文檔的點贊數(shù)+1commentService.updateCommentLikenum("3");}
GITHUB
代碼倉庫
https://github.com/onenewcode/MyMongoDB.git