5.6 文章评论的基本增删改查
(1)创建数据访问接口 cn.itcast.article包下创建dao包,包下创建接口
cn.itcast.article.dao.CommentRepository
package cn.itcast.article.dao; import cn.itcast.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> { }
(2)创建业务逻辑类 cn.itcast.article包下创建service包,包下创建类
cn.itcast.article.service.CommentService
package cn.itcast.article.service; import cn.itcast.article.dao.CommentRepository; import cn.itcast.article.po.Comment; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; //评论的业务层 public class CommentService { //注入dao private CommentRepository commentRepository; /** * 保存一个评论 * @param comment */ public void saveComment(Comment comment){ //如果需要自定义主键,可以在这里指定主键;如果不指定主键,MongoDB会自动生成主键 //设置一些默认初始值。。。 //调用dao commentRepository.save(comment); } /** * 更新评论 * @param comment */ public void updateComment(Comment comment){ //调用dao commentRepository.save(comment); } /** * 根据id删除评论 * @param id */ public void deleteCommentById(String id){ //调用dao commentRepository.deleteById(id); } /** * 查询所有评论 * @return */ public List<Comment> findCommentList(){ //调用dao return commentRepository.findAll(); } /** * 根据id查询评论 * @param id * @return */ public Comment findCommentById(String id){ //调用dao return commentRepository.findById(id).get(); } }
(3)新建Junit测试类,测试保存和查询所有:
cn.itcast.article.service.CommentServiceTest
package cn.itcast.article.service; import cn.itcast.article.ArticleApplication; import cn.itcast.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; //测试评论的业务层 //SpringBoot的Junit集成测试 SpringRunner.class) (//SpringBoot的测试环境初始化,参数:启动类 classes = ArticleApplication.class) (public class CommentServiceTest { //注入Service private CommentService commentService; /** * 保存一个评论 */ public void testSaveComment(){ Comment comment=new Comment(); comment.setArticleid("100000"); comment.setContent("测试添加的数据"); comment.setCreatedatetime(LocalDateTime.now()); comment.setUserid("1003"); comment.setNickname("凯撒大帝"); comment.setState("1"); comment.setLikenum(0); comment.setReplynum(0); commentService.saveComment(comment); } /** * 查询所有数据 */ public void testFindAll(){ List<Comment> list = commentService.findCommentList(); System.out.println(list); } /** * 测试根据id查询 */ public void testFindCommentById(){ Comment comment = commentService.findCommentById("5d6a27b81b8d374798cf0b41"); System.out.println(comment); } }
添加结果: