文章目录

  • pojo层
    • mybatis-plus
    • jpa:
  • service层
    • mybatis-plus:
    • jpa:
  • repository层
    • mybatis-plus
    • jpa:
  • 总结

总觉得二者在写法上有相似之处,遂今日想总结一下两个项目中的写法对比。
拿评论功能举例:

pojo层

mybatis-plus

@Data
@Builder
//通过@Builder注解,lombok还可以方便的时间建造者模式。
@AllArgsConstructor
@NoArgsConstructor
@TableName("tb_comment")
public class Comment {/*** id*/@TableId(value = "id", type = IdType.AUTO)private Integer id;/*** 评论用户Id*/private Integer userId;/*** 回复用户id*/private Integer replyUserId;/*** 评论文章id*/private Integer articleId;/*** 评论内容*/private String commentContent;/*** 父评论id*/private Integer parentId;/*** 是否审核*/private Integer isReview;/*** 创建时间*/@TableField(fill = FieldFill.INSERT)private LocalDateTime createTime;/*** 修改时间*/@TableField(fill = FieldFill.UPDATE)private LocalDateTime updateTime;}

jpa:

@Data
@Entity
@Table(name = "t_comment")
public class Comment {@Id@GeneratedValueprivate Long id;private String nickname;private String email;private String content;private String avatar;@Temporal(TemporalType.TIMESTAMP)private Date createTime;@ManyToOneprivate Blog blog;@OneToMany(mappedBy = "parentComment")private List<Comment> replyComments = new ArrayList<>();@ManyToOneprivate Comment parentComment;private boolean adminComment;

service层

mybatis-plus:

public interface CommentService extends IService<Comment> {/*** 查看评论** @param articleId 文章id* @return 评论列表*/PageResult<CommentDTO> listComments(Integer articleId);/*** 查看评论下的回复** @param commentId 评论id* @return 回复列表*/List<ReplyDTO> listRepliesByCommentId(Integer commentId);/*** 添加评论** @param commentVO 评论对象*/void saveComment(CommentVO commentVO);/*** 点赞评论** @param commentId 评论id*/void saveCommentLike(Integer commentId);/*** 审核评论** @param reviewVO 审核信息*/void updateCommentsReview(ReviewVO reviewVO);/*** 查询后台评论** @param condition 条件* @return 评论列表*/PageResult<CommentBackDTO> listCommentBackDTO(ConditionVO condition);}

实现类

@Service
public class CommentServiceImpl extends ServiceImpl<CommentDao, Comment> implements CommentService {@Autowiredprivate CommentDao commentDao;@Autowiredprivate ArticleDao articleDao;@Autowiredprivate UserInfoDao userInfoDao;@Autowiredprivate BlogInfoService blogInfoService;@Overridepublic PageResult<CommentDTO> listComments(Integer articleId) {// 查询文章评论量Integer commentCount = commentDao.selectCount(new LambdaQueryWrapper<Comment>().eq(Objects.nonNull(articleId), Comment::getArticleId, articleId).isNull(Objects.isNull(articleId), Comment::getArticleId).isNull(Comment::getParentId).eq(Comment::getIsReview, TRUE));if (commentCount == 0) {return new PageResult<>();}// 分页查询评论集合List<CommentDTO> commentDTOList = commentDao.listComments(PageUtils.getLimitCurrent(), PageUtils.getSize(), articleId);if (CollectionUtils.isEmpty(commentDTOList)) {return new PageResult<>();}// 查询redis的评论点赞数据Map<String, Object> likeCountMap = redisService.hGetAll(COMMENT_LIKE_COUNT);// 提取评论id集合List<Integer> commentIdList = commentDTOList.stream().map(CommentDTO::getId).collect(Collectors.toList());// 根据评论id集合查询回复数据List<ReplyDTO> replyDTOList = commentDao.listReplies(commentIdList);// 封装回复点赞量replyDTOList.forEach(item -> item.setLikeCount((Integer) likeCountMap.get(item.getId().toString())));// 根据评论id分组回复数据Map<Integer, List<ReplyDTO>> replyMap = replyDTOList.stream().collect(Collectors.groupingBy(ReplyDTO::getParentId));// 根据评论id查询回复量Map<Integer, Integer> replyCountMap = commentDao.listReplyCountByCommentId(commentIdList).stream().collect(Collectors.toMap(ReplyCountDTO::getCommentId, ReplyCountDTO::getReplyCount));// 封装评论数据commentDTOList.forEach(item -> {item.setLikeCount((Integer) likeCountMap.get(item.getId().toString()));item.setReplyDTOList(replyMap.get(item.getId()));item.setReplyCount(replyCountMap.get(item.getId()));});return new PageResult<>(commentDTOList, commentCount);}@Overridepublic List<ReplyDTO> listRepliesByCommentId(Integer commentId) {// 转换页码查询评论下的回复List<ReplyDTO> replyDTOList = commentDao.listRepliesByCommentId(PageUtils.getLimitCurrent(), PageUtils.getSize(), commentId);// 查询redis的评论点赞数据Map<String, Object> likeCountMap = redisService.hGetAll(COMMENT_LIKE_COUNT);// 封装点赞数据replyDTOList.forEach(item -> item.setLikeCount((Integer) likeCountMap.get(item.getId().toString())));return replyDTOList;}@Transactional(rollbackFor = Exception.class)@Overridepublic void saveComment(CommentVO commentVO) {// 判断是否需要审核Integer isReview = websiteConfig.getIsCommentReview();// 过滤标签commentVO.setCommentContent(HTMLUtils.deleteTag(commentVO.getCommentContent()));Comment comment = Comment.builder().userId(UserUtils.getLoginUser().getUserInfoId()).replyUserId(commentVO.getReplyUserId()).articleId(commentVO.getArticleId()).commentContent(commentVO.getCommentContent()).parentId(commentVO.getParentId()).isReview(isReview == TRUE ? FALSE : TRUE).build();commentDao.insert(comment);// 判断是否开启邮箱通知,通知用户if (websiteConfig.getIsEmailNotice().equals(TRUE)) {notice(comment);}}@Transactional(rollbackFor = Exception.class)@Overridepublic void updateCommentsReview(ReviewVO reviewVO) {// 修改评论审核状态List<Comment> commentList = reviewVO.getIdList().stream().map(item -> Comment.builder().id(item).isReview(reviewVO.getIsReview()).build()).collect(Collectors.toList());this.updateBatchById(commentList);}@Overridepublic PageResult<CommentBackDTO> listCommentBackDTO(ConditionVO condition) {// 统计后台评论量Integer count = commentDao.countCommentDTO(condition);if (count == 0) {return new PageResult<>();}

注意条件构造语句:

 Integer commentCount = commentDao.selectCount(new LambdaQueryWrapper<Comment>().eq(Objects.nonNull(articleId), Comment::getArticleId, articleId).isNull(Objects.isNull(articleId), Comment::getArticleId).isNull(Comment::getParentId).eq(Comment::getIsReview, TRUE));if (commentCount == 0) {return new PageResult<>();}

jpa:

public interface CommentService {List<Comment> listCommentByBlogId(Long blogId);Comment saveComment(Comment comment);
}
@Service
public class CommentServiceImpl implements CommentService {@Autowiredprivate CommentRepository commentRepository;@Overridepublic List<Comment> listCommentByBlogId(Long blogId) {Sort sort = Sort.by("createTime");List<Comment> comments = commentRepository.findByBlogIdAndParentCommentNull(blogId,sort);return eachComment(comments);}@Transactional@Overridepublic Comment saveComment(Comment comment) {Long parentCommentId = comment.getParentComment().getId();if (parentCommentId != -1) {comment.setParentComment(commentRepository.getOne(parentCommentId));} else {comment.setParentComment(null);}comment.setCreateTime(new Date());return commentRepository.save(comment);}/*** 循环每个顶级的评论节点* @param comments* @return*/private List<Comment> eachComment(List<Comment> comments) {List<Comment> commentsView = new ArrayList<>();for (Comment comment : comments) {Comment c = new Comment();BeanUtils.copyProperties(comment,c);commentsView.add(c);}//合并评论的各层子代到第一级子代集合中combineChildren(commentsView);return commentsView;}/**** @param comments root根节点,blog不为空的对象集合* @return*/private void combineChildren(List<Comment> comments) {for (Comment comment : comments) {List<Comment> replys1 = comment.getReplyComments();for(Comment reply1 : replys1) {//循环迭代,找出子代,存放在tempReplys中recursively(reply1);}//修改顶级节点的reply集合为迭代处理后的集合comment.setReplyComments(tempReplys);//清除临时存放区tempReplys = new ArrayList<>();}}//存放迭代找出的所有子代的集合private List<Comment> tempReplys = new ArrayList<>();/*** 递归迭代,剥洋葱* @param comment 被迭代的对象* @return*/private void recursively(Comment comment) {tempReplys.add(comment);//顶节点添加到临时存放集合if (comment.getReplyComments().size()>0) {List<Comment> replys = comment.getReplyComments();for (Comment reply : replys) {tempReplys.add(reply);if (reply.getReplyComments().size()>0) {recursively(reply);}}}}
}

repository层

mybatis-plus

@Repository
public interface CommentDao extends BaseMapper<Comment> {/*** 评论列表* 查看评论** @param articleId 文章id* @param current   当前页码* @param size      大小* @return 评论集合*/List<CommentDTO> listComments(@Param("current") Long current, @Param("size") Long size, @Param("articleId") Integer articleId);/*** 查看评论id集合下的回复** @param commentIdList 评论id集合* @return 回复集合*/List<ReplyDTO> listReplies(@Param("commentIdList") List<Integer> commentIdList);/*** 查看当条评论下的回复** @param commentId 评论id* @param current   当前页码* @param size      大小* @return 回复集合*/List<ReplyDTO> listRepliesByCommentId(@Param("current") Long current, @Param("size") Long size, @Param("commentId") Integer commentId);/*** 根据评论id查询回复总量** @param commentIdList 评论id集合* @return 回复数量*/List<ReplyCountDTO> listReplyCountByCommentId(@Param("commentIdList") List<Integer> commentIdList);/*** 查询后台评论** @param current   页码* @param size      大小* @param condition 条件* @return 评论集合*/List<CommentBackDTO> listCommentBackDTO(@Param("current") Long current, @Param("size") Long size, @Param("condition") ConditionVO condition);/*** 统计后台评论数量** @param condition 条件* @return 评论数量*/Integer countCommentDTO(@Param("condition") ConditionVO condition);}

xml:

?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.minzheng.blog.dao.CommentDao"><select id="listComments" resultType="com.blog.dto.CommentDTO">SELECTu.nickname,u.avatar,u.web_site,c.user_id,c.id,c.comment_content,c.create_timeFROMtb_comment cJOIN tb_user_info u ON c.user_id = u.idWHERE<if test="articleId != null">article_id = #{articleId}</if><if test="articleId == null">article_id IS NULL</if>AND c.is_review = 1AND parent_id IS NULLORDER BYc.id DESCLIMIT #{current},#{size}</select><select id="listReplies" resultType="com.minzheng.blog.dto.ReplyDTO">SELECT*FROM(SELECTc.user_id,u.nickname,u.avatar,u.web_site,c.reply_user_id,r.nickname AS reply_nickname,r.web_site AS reply_web_site,c.id,c.parent_id,c.comment_content,c.create_time,row_number () over ( PARTITION BY parent_id ORDER BY create_time ASC ) row_numFROMtb_comment cJOIN tb_user_info u ON c.user_id = u.idJOIN tb_user_info r ON c.reply_user_id = r.idWHEREc.is_review = 1ANDparent_id IN(<foreach collection="commentIdList" item="commentId" separator=",">#{commentId}</foreach>)) tWHERE4 > row_num</select><select id="listReplyCountByCommentId" resultType="com.minzheng.blog.dto.ReplyCountDTO">SELECTparent_id as comment_id,count(1) AS reply_countFROMtb_commentWHEREis_review = 1ANDparent_id IN(<foreach collection="commentIdList" item="commentId" separator=",">#{commentId}</foreach>)GROUP BYparent_id</select><select id="listRepliesByCommentId" resultType="com.minzheng.blog.dto.ReplyDTO">SELECTc.user_id,u.nickname,u.avatar,u.web_site,c.reply_user_id,r.nickname as reply_nickname,r.web_site as reply_web_site,c.id,c.parent_id,c.comment_content,c.create_timeFROMtb_comment cJOIN tb_user_info u ON c.user_id = u.idJOIN tb_user_info r ON c.reply_user_id = r.idWHEREc.is_review = 1ANDparent_id =#{commentId}ORDER BYc.id ASCLIMIT #{current}, #{size}</select><select id="countCommentDTO" resultType="java.lang.Integer">SELECTcount(1)fromtb_comment cLEFT JOIN tb_user_info u ON c.user_id = u.id<where><if test="condition.type != null and condition.type == 1">c.article_id IS NOT NULL</if><if test="condition.type != null and condition.type == 2">c.article_id IS NULL</if><if test="condition.isReview != null">c.is_review = #{condition.isReview}</if><if test="condition.keywords != null">and u.nickname like concat('%',#{condition.keywords},'%')</if></where></select></mapper>

jpa:

public interface CommentRepository extends JpaRepository<Comment,Long>{List<Comment> findByBlogIdAndParentCommentNull(Long blogId, Sort sort);
}

总结

注意,getOne和save方法都是jpa自带的
insert updateBatchById是mybatis-plus的

mybatis-plus与jpa在操作数据库时写法对比相关推荐

  1. 解决spring boot+JPA实现操作数据库时编辑时也变成了新增

    场景:使用spring boot+JPA框架开发项目的时候,新增数据是正常的,但是编辑有时候会变成新增,JPA判断是否新增对象有两个方法:1根据id,2根据版本号.我在开发项目中用的是根据版本号进行判 ...

  2. Mybatis介绍、jdbc操作数据库原始写法以及Mybatis架构

    文章目录 Mybatis介绍 jdbc操作数据库原生写法 使用jdbc编程问题总结 Mybatis架构 Mybatis介绍 MyBatis 本是apache的一个开源项目iBatis, 2010年这个 ...

  3. 多线程操作数据库时为了防止数据的增删改的混乱该在数据库层还是程序层面上进行同步?

    多线程操作数据库时为了防止数据的增删改的混乱该在数据库层还是程序层面上进行同步? [问题点数:60分,结帖人jiao_zg] 不显示删除回复 显示所有回复 显示星级回复 显示得分回复 只显示楼主 收藏 ...

  4. java连接本地数据库命令_Java操作数据库时一次连接只能执行一条SQL命令

    Java操作数据库时一次连接只能执行一条SQL命令 答:× 全面深化改革要攻坚涉险,必须坚持正确的思想方法,不断探索和把握全面深化改革的内在规律,特别是要把握和处理好全面深化改革中的等重大关系 答:整 ...

  5. JPA连接Mysql数据库时提示:Table 'jpa.sequence' dosen't exisit

    场景 在使用JPA连接Mysql数据库进行数据持久化时提示: Table 'jpa.sequence' dosen't exist 注: 博客主页: https://blog.csdn.net/bad ...

  6. JDBC:使用Statement操作数据库时产生的SQL注入问题原因分析

    SQL注入问题简单介绍 1.JDBC中使用Stement对数据库增删改查, 执行sql语句时使用拼接字符串会导致SQL注入 2.JDBC中使用PreaparedStement可以有效避免SQL注入问题 ...

  7. 使用ADO操作数据库时一个好用的VARIANT类!

    inline CString VTOCSTR(VARIANT *v) {  if(v->vt==VT_BSTR)  {   CString str((LPCWSTR)v->bstrVal) ...

  8. python向数据库中添加参数_第四篇:python操作数据库时的传参问题

    python在操作数据库执行sql的时候我们经常会遇到传参问题,以下是我总结的几种方法: 1.格式化字符串 city = 'beijing' cur.execute("SELECT * FR ...

  9. Navicat操作数据库时一直显示加载中

    用Navicat for mysql操作mysql数据库,其中一个表怎么也打不开,一直加载,还不能关闭.从网上搜索原因,主要是以下几个原因: 原因一: 表死锁,会出现这样的情况,锁不释放,无论多久都读 ...

最新文章

  1. 【Linux】Linux computer文件夹下各种文件的作用
  2. gatsby_将您的GraphCMS数据导入Gatsby
  3. SDN控制器OpenDaylight简介—VeCloud
  4. c char转int_C指针精华知识大汇总
  5. 直播 | 清华大学李一鸣:后门攻击简介
  6. 求取给定的二叉树的镜像_17---二叉树的镜像
  7. iOS 两个tableview的 瀑布流
  8. dcom配置_spring cloud 二代架构依赖组件 全配置放送
  9. html 通用ui css图标,ui-icon.html
  10. 基于TCP的Socket网络编程,有图有代码
  11. Coprime Sequence
  12. 移动互联网创新39个热点
  13. RabbitMQ03高级篇(消息可靠性投递,Consumer ACK,消费端限流,TTL, 通过代码创建队列和交换机以及绑定)
  14. spyder的变量窗口显示不全
  15. Webots学习笔记—四轮小车的模型搭建和简单控制
  16. 织梦CMS首页被篡改怎么办?
  17. Pytorch——报错解决:匈牙利匹配
  18. 云原生微服务架构实战精讲第八节 访问控制与更新策略
  19. ViveInputUtility-手柄触摸3D物体(6)
  20. Python 3 条件判断和循环语句,list、tuple、dict、set容器,部分函数

热门文章

  1. mysqli num php_php mysqli_num_rows函数怎么用
  2. 机器人专用符文_英雄联盟【LOL】手游部分英雄天赋符文和出装推荐
  3. HTML字体怎么显示,教你如何用CSS来控制网页字体的显示样式
  4. php curl ssr,php curl模拟登陆
  5. python建立字典读取键和值_在Python字典中动态创建键和值
  6. python模块批量安装方法_python离线批量安装依赖包
  7. dev chartcontrol获取x y轴的值_终于,奔驰强势接手了腾势X
  8. linux用avk怎么提取字符,在Linux下进行视频音频格式转换提取等
  9. 四、数据仓库和Hive环境搭建
  10. 二、数据分析前,打下数据处理基础(上)