From bc20173084dbb722fed6aaa53bd14716eb46db4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Sat, 23 May 2020 00:16:08 +0800 Subject: [PATCH 01/33] =?UTF-8?q?=E6=95=B0=E6=8D=AE=E8=A1=A8=E6=94=B9?= =?UTF-8?q?=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- newBlog.sql | 166 ++++++++++++++++++ .../blog/enmu/UserAccountStatusEnum.java | 41 +++++ 2 files changed, 207 insertions(+) create mode 100644 newBlog.sql create mode 100644 src/main/java/cn/celess/blog/enmu/UserAccountStatusEnum.java diff --git a/newBlog.sql b/newBlog.sql new file mode 100644 index 0000000..62d6357 --- /dev/null +++ b/newBlog.sql @@ -0,0 +1,166 @@ +CREATE DATABASE `t_blog`; + +USE t_blog; + +CREATE TABLE `article` +( + `a_id` bigint(20) primary key auto_increment, + `a_title` varchar(255) not null unique comment '文章标题', + `a_summary` varchar(255) not null comment '文章摘要', + `a_md_content` longtext not null comment '文章Markdown内容', + `a_url` tinytext default null comment '转载文章的原文链接', + `a_author_id` int not null comment '作者id', + `a_is_original` boolean default true comment '文章是否原创', + `a_reading_number` int default 0 comment '文章阅读数', + `a_like` int default 0 comment '文章点赞数', + `a_dislike` int default 0 comment '文章不喜欢数', + `a_category_id` int not null comment '文章分类id', + `a_publish_date` datetime default CURRENT_TIMESTAMP comment '文章发布时间', + `a_update_date` datetime default null comment '文章的更新时间', + `a_is_open` boolean default true comment '文章是否可见', + `is_delete` boolean not null default false comment '该数据是否被删除' +) DEFAULT CHARSET = utf8mb4 + COLLATE utf8mb4_general_ci,comment '文章表'; + +CREATE TABLE `article_tag` +( + `at_id` bigint(20) primary key auto_increment, + `a_id` bigint(20) not null comment '文章id', + `t_id` bigint not null comment 'tag/category 的id' +) comment '文章标签表'; + +CREATE TABLE `tag_category` +( + `t_id` bigint(20) primary key auto_increment, + `t_name` varchar(255) not null, + `is_category` boolean not null default true, + `is_delete` boolean not null default false comment '该数据是否被删除' +) comment '标签和分类表'; + +CREATE TABLE `comment` +( + `co_id` bigint(20) primary key auto_increment, + `co_page_path` varchar(255) not null comment '评论/留言的页面', + `co_content` text not null comment '评论/留言内容', + `co_date` datetime not null comment '评论/留言的日期', + `co_status` tinyint not null default 0 comment '评论的状态', + `co_pid` bigint not null default -1 comment '评论/留言的父id', + `co_from_author_id` int not null comment '留言者id', + `co_to_author_id` int default null comment '父评论的作者id', + `is_delete` boolean not null default false comment '该数据是否被删除' +) DEFAULT CHARSET = utf8mb4 + COLLATE utf8mb4_general_ci,comment '评论/留言表'; + + + +CREATE TABLE `links` +( + `l_id` bigint(20) primary key auto_increment, + `l_name` varchar(255) not null comment '友站名称', + `l_is_open` boolean default true comment '是否公开', + `l_url` varchar(255) not null comment '首页地址', + `l_icon_path` varchar(255) not null comment '友链的icon地址', + `l_desc` varchar(255) not null comment '友链的说明描述', + `is_delete` boolean not null default false comment '该数据是否被删除' +) comment '友站表'; + +CREATE TABLE `visitor` +( + `v_id` bigint(20) primary key auto_increment, + `v_date` datetime not null comment '访问时间', + `v_ip` varchar(255) not null comment '访客ip', + `v_user_agent` text comment '访客ua', + `is_delete` boolean not null default false comment '该数据是否被删除' +) comment '访客表'; + +CREATE TABLE `web_update` +( + `wu_id` int primary key auto_increment, + `wu_info` varchar(255) not null comment '更新内容', + `wu_time` datetime not null comment '更新时间', + `is_delete` boolean not null default false comment '该数据是否被删除' +) comment '更新内容表'; + +CREATE TABLE `user` +( + `u_id` int not null primary key auto_increment, + `u_email` varchar(50) not null, + `u_pwd` varchar(40) not null comment '密码', + `u_email_status` boolean default false comment '邮箱验证状态', + `u_avatar` varchar(255) default null comment '用户头像', + `u_desc` tinytext default null comment '用户的描述', + `u_recently_landed_time` datetime default null comment '最近的登录时间', + `u_display_name` varchar(30) default null comment '展示的昵称', + `u_role` varchar(40) not null default 'user' comment '权限组', + `status` tinyint(1) not null default 0 comment '账户状态', + unique key `uni_user_id` (`u_id`), + unique key `uni_user_email` (`u_email`) +) comment '用户表'; + + +CREATE VIEW articleView + (articleId, title, summary, mdContent, url, isOriginal, readingCount, likeCount, dislikeCount, + publishDate, updateDate, isOpen, + categoryId, categoryName, tagId, tagName, + authorId, userEmail, userAvatar, userDisplayName, isDelete) +as +select article.a_id as articleId, + article.a_title as title, + article.a_summary as summary, + article.a_md_content as mdContent, + article.a_url as url, + article.a_is_original as isOriginal, + article.a_reading_number as readingCount, + article.a_like as likeCount, + article.a_dislike as dislikeCount, + article.a_publish_date as publishDate, + article.a_update_date as updateDate, + article.a_is_open as isOpen, + category.t_id as categoryId, + category.t_name as categoryName, + tag.t_id as tagId, + tag.t_name as tagName, + user.u_id as authorId, + user.u_email as userEmail, + user.u_avatar as userAvatar, + user.u_display_name as userDisplayName, + article.is_delete as isDelete +from article, + tag_category as tag, + tag_category as category, + article_tag, + user +where article.a_id = article_tag.a_id + and article_tag.t_id = tag.t_id + and tag.is_category = false + and article.a_category_id = category.t_id + and category.is_category = true + and article.a_author_id = user.u_id; + +CREATE VIEW commentView + (commentId, pagePath, content, date, status, pid, + fromAuthorId, fromAuthorEmail, fromAuthorDisplayName, fromAuthorAvatar, toAuthorId, + toAuthorEmail, toAuthorDisplayName, toAuthorAvatar, isDelete + ) +as +select comment.co_id as commentId, + comment.co_page_path as pagePath, + comment.co_content as content, + comment.co_date as date, + comment.co_status as status, + comment.co_pid as pid, + comment.co_from_author_id as fromAuthorId, + userFrom.u_email as fromAuthorEmail, + userFrom.u_display_name as fromAuthorDisplayName, + userFrom.u_avatar as fromAuthorAvatar, + comment.co_to_author_id as toAuthorId, + userTo.u_email as toAuthorEmail, + userTo.u_display_name as toAuthorDisplayName, + userTo.u_avatar as toAuthorAvatar, + comment.is_delete as isDelete +from comment, + user as userFrom, + user as userTo +where comment.co_from_author_id = userFrom.u_id + and comment.co_to_author_id = userTo.u_id; + diff --git a/src/main/java/cn/celess/blog/enmu/UserAccountStatusEnum.java b/src/main/java/cn/celess/blog/enmu/UserAccountStatusEnum.java new file mode 100644 index 0000000..3d235bb --- /dev/null +++ b/src/main/java/cn/celess/blog/enmu/UserAccountStatusEnum.java @@ -0,0 +1,41 @@ +package cn.celess.blog.enmu; + +import lombok.Data; + +/** + * @Author: 小海 + * @Date: 2020-05-22 21:32 + * @Desc: + */ +public enum UserAccountStatusEnum { + + /** + * 账户正常 + */ + NORMAL(0, "正常"), + /** + * 账户被锁定 + */ + LOCKED(1, "锁定"), + /** + * 账户被删除 + */ + DELETED(2, "已删除"); + + + private final int code; + private final String desc; + + private UserAccountStatusEnum(int code, String desc) { + this.code = code; + this.desc = desc; + } + + public int getCode() { + return code; + } + + public String getDesc() { + return desc; + } +} From 9b6293fbebc7e2ecc4ef626ec31bf296102e14a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Sat, 23 May 2020 13:27:30 +0800 Subject: [PATCH 02/33] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E8=AF=AD=E5=8F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/cn/celess/blog/entity/Article.java | 15 ++ .../cn/celess/blog/mapper/ArticleMapper.java | 8 +- src/main/resources/mapper/CategoryMapper.xml | 4 +- src/main/resources/mapper/articleMapper.xml | 114 +++++++++------ .../celess/blog/mapper/ArticleMapperTest.java | 134 ++++++++++++++++++ 5 files changed, 225 insertions(+), 50 deletions(-) create mode 100644 src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java diff --git a/src/main/java/cn/celess/blog/entity/Article.java b/src/main/java/cn/celess/blog/entity/Article.java index 29b865c..496a1d3 100644 --- a/src/main/java/cn/celess/blog/entity/Article.java +++ b/src/main/java/cn/celess/blog/entity/Article.java @@ -3,6 +3,7 @@ package cn.celess.blog.entity; import lombok.Data; import java.util.Date; +import java.util.List; /** * @author : xiaohai @@ -41,14 +42,19 @@ public class Article { private Date updateDate = null; + @Deprecated private Long categoryId; + @Deprecated private String tagsId; + @Deprecated private Long authorId; + @Deprecated private Long preArticleId; + @Deprecated private Long nextArticleId; private Long readingNumber; @@ -58,4 +64,13 @@ public class Article { */ private Boolean open; + private Category category; + + private List tags; + + private Integer likeCount; + + private Integer dislikeCount; + + private User user; } diff --git a/src/main/java/cn/celess/blog/mapper/ArticleMapper.java b/src/main/java/cn/celess/blog/mapper/ArticleMapper.java index aef3de4..c5b6e1d 100644 --- a/src/main/java/cn/celess/blog/mapper/ArticleMapper.java +++ b/src/main/java/cn/celess/blog/mapper/ArticleMapper.java @@ -21,10 +21,13 @@ public interface ArticleMapper { int update(Article a); + @Deprecated int updateNextArticleId(long targetArticleID, long nextArticleID); + @Deprecated int updatePreArticleId(long targetArticleID, long preArticleID); + @Deprecated long getLastestArticleId(); Article getLastestArticle(); @@ -33,7 +36,7 @@ public interface ArticleMapper { boolean existsByTitle(String title); - boolean existsById(long id); + boolean isDeletedById(long id); List
findAllByAuthorId(long authorID); @@ -51,8 +54,11 @@ public interface ArticleMapper { List
getSimpleInfoByTag(List idList); + @Deprecated int setReadingNumber(long number, long id); + int updateReadingNumber(long id); + long count(); } diff --git a/src/main/resources/mapper/CategoryMapper.xml b/src/main/resources/mapper/CategoryMapper.xml index 0a0c444..6f343b1 100644 --- a/src/main/resources/mapper/CategoryMapper.xml +++ b/src/main/resources/mapper/CategoryMapper.xml @@ -2,8 +2,8 @@ - - + + diff --git a/src/main/resources/mapper/articleMapper.xml b/src/main/resources/mapper/articleMapper.xml index e994535..fd2059d 100644 --- a/src/main/resources/mapper/articleMapper.xml +++ b/src/main/resources/mapper/articleMapper.xml @@ -6,78 +6,91 @@ - - - - + + + + + + - - insert into article (a_author_id, a_category_id, a_tags_id, a_md_content, a_publish_date, + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into article (a_author_id, a_category_id, a_md_content, a_publish_date, a_summary, a_title, a_url) - values (#{authorId}, #{categoryId}, #{tagsId}, #{mdContent}, #{publishDate}, + values (#{user.id}, #{category.id}, #{mdContent}, #{publishDate}, #{summary}, #{title}, #{url}) - - SELECT LAST_INSERT_ID() AS id - - - delete - from article + + update article + set is_delete = true where a_id = #{id} - + update article - set + set a_update_date=now(), a_title=#{title}, a_md_content=#{mdContent}, a_summary=#{summary}, a_is_original=#{type}, a_url=#{url}, - a_update_date=#{updateDate}, - a_category_id=#{categoryId}, - a_tags_id=#{tagsId}, - next_a_id=#{nextArticleId}, - pre_a_id=#{preArticleId}, + a_category_id=#{category.id}, a_is_open=#{open} where a_id = #{id} - + update article - set next_a_id=#{nextArticleID} - where a_id = #{targetArticleID} - - - - update article - set pre_a_id=#{preArticleID} - where a_id = #{targetArticleID} - - - update article - set a_reading_number=#{number} + set a_reading_number=a_reading_number + 1 where a_id = #{id} - - @@ -85,16 +98,22 @@ - + select is_delete + from article + WHERE a_id = #{id} +# SELECT EXISTS(SELECT * FROM article - select * - from article - order by a_id desc + from articleView + where isDelete = false + order by articleId desc select * - from category - where c_name = #{name} + from tag_category + where t_name = #{name} + and is_category = true; - + select t_id + from tag_category + where is_category = true + and t_name = #{name} \ No newline at end of file diff --git a/src/main/resources/mapper/articleMapper.xml b/src/main/resources/mapper/articleMapper.xml index fd2059d..7dc1e18 100644 --- a/src/main/resources/mapper/articleMapper.xml +++ b/src/main/resources/mapper/articleMapper.xml @@ -7,7 +7,7 @@ - + @@ -15,11 +15,12 @@ - + - + @@ -37,6 +38,7 @@ + @@ -55,10 +57,9 @@ - insert into article (a_author_id, a_category_id, a_md_content, a_publish_date, + insert into article (a_author_id, a_category_id, a_md_content, a_is_original, a_summary, a_title, a_url) - values (#{user.id}, #{category.id}, #{mdContent}, #{publishDate}, - #{summary}, #{title}, #{url}) + values (#{user.id}, #{category.id}, #{mdContent}, #{type}, #{summary}, #{title}, #{url}) update article @@ -85,24 +86,18 @@ where a_id = #{id} - select * - from article, - tag_category - where tag_category.is_category = true - and article.a_category_id = tag_category.t_id - order by a_id desc + from articleView + order by articleId desc limit 1 - select * - from article, - tag_category - where a_id = #{id} - and tag_category.is_category = true - and article.a_category_id = tag_category.t_id + from articleView + where articleId = #{id} - select * - from article - where a_author_id = #{authorID} - order by a_id desc + from articleView + where authorId = #{authorID} + and isDelete = false + order by articleId desc - select * - from article - where a_is_open = #{isOpen} - order by a_id desc + from articleView + where isOpen = #{isOpen} + and isDelete = false + order by articleId desc - + select * + from articleView + where categoryId = #{id} + and isDelete = false + order by articleId desc + - - - - - - + \ No newline at end of file diff --git a/src/main/resources/mapper/tagMapper.xml b/src/main/resources/mapper/tagMapper.xml index 7c976e9..536ccf6 100644 --- a/src/main/resources/mapper/tagMapper.xml +++ b/src/main/resources/mapper/tagMapper.xml @@ -1,75 +1,66 @@ - - - + + + - - insert into tag (tag_name, articles) - VALUES (#{name}, #{articles}); - - SELECT LAST_INSERT_ID() AS id - + + insert into tag_category (t_name, is_category) + VALUES (#{name}, false); - update tag - set tag_name=#{name}, - articles=#{articles} - where tag_id = #{id} + update tag_category + set t_name=#{name} + where t_id = #{id} + and is_category = false; - - delete - from tag - where tag_id = #{id} - + + update tag_category + set is_delete = true + where t_id = #{id} + and is_category = false; + - - - - - \ No newline at end of file diff --git a/src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java b/src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java index bfa7cb8..1275e91 100644 --- a/src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java +++ b/src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java @@ -1,10 +1,7 @@ package cn.celess.blog.mapper; import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.Article; -import cn.celess.blog.entity.Category; -import cn.celess.blog.entity.Tag; -import cn.celess.blog.entity.User; +import cn.celess.blog.entity.*; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -16,37 +13,38 @@ import static org.junit.Assert.*; public class ArticleMapperTest extends BaseTest { @Autowired ArticleMapper articleMapper; + @Autowired + TagMapper tagMapper; + @Autowired + ArticleTagMapper articleTagMapper; @Test public void insert() { - Article article = generateArticle(); - - articleMapper.insert(article); + Article article = generateArticle().getArticle(); assertNotNull(article.getId()); } @Test public void delete() { - Article article = generateArticle(); + Article article = generateArticle().getArticle(); - articleMapper.insert(article); assertFalse(articleMapper.isDeletedById(article.getId())); assertEquals(1, articleMapper.delete(article.getId())); assertTrue(articleMapper.isDeletedById(article.getId())); + + } @Test public void update() { - Article article = generateArticle(); + Article article = generateArticle().getArticle(); String randomText = UUID.randomUUID().toString(); // 此字段不会通过insert被写入数据库而是使用插入数据的默认值 数据库中该字段默认为true article.setOpen(true); - articleMapper.insert(article); - article.setTitle("test update " + randomText); article.setMdContent("test update "); article.setSummary("test update "); @@ -93,8 +91,7 @@ public class ArticleMapperTest extends BaseTest { @Test public void updateReadCount() { - Article article = generateArticle(); - articleMapper.insert(article); + Article article = generateArticle().getArticle(); Article articleById = articleMapper.findArticleById(article.getId()); assertEquals(Long.valueOf(0), articleById.getReadingNumber()); articleMapper.updateReadingNumber(articleById.getId()); @@ -105,17 +102,16 @@ public class ArticleMapperTest extends BaseTest { @Test public void getLastestArticle() { - Article article = generateArticle(); - articleMapper.insert(article); + Article article = generateArticle().getArticle(); Article lastestArticle = articleMapper.getLastestArticle(); assertNotNull(lastestArticle); assertEquals(article.getId(), lastestArticle.getId()); - // assertNotNull(lastestArticle.getCategory()); - // assertNotEquals(0, lastestArticle.getTags().size()); + assertNotNull(lastestArticle.getCategory()); + assertNotEquals(0, lastestArticle.getTags().size()); } - private Article generateArticle() { + private ArticleTag generateArticle() { String randomText = UUID.randomUUID().toString(); Article article = new Article(); @@ -125,10 +121,20 @@ public class ArticleMapperTest extends BaseTest { article.setTitle(" unity test for article " + randomText); article.setMdContent("# unity test for article"); article.setSummary("unity test for article"); + + Tag tag = tagMapper.findTagByName("随笔"); User user = new User(); user.setId(1L); article.setUser(user); article.setType(true); - return article; + + articleMapper.insert(article); + + ArticleTag articleTag = new ArticleTag(); + articleTag.setArticle(article); + articleTag.setTag(tag); + articleTagMapper.insert(articleTag); + + return articleTag; } } \ No newline at end of file From 87de48b5a089db763555cf3a4e08552bbeba8f2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Sun, 24 May 2020 22:00:06 +0800 Subject: [PATCH 04/33] =?UTF-8?q?dao=E5=B1=82=E4=BF=AE=E6=94=B9=20=20?= =?UTF-8?q?=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/cn/celess/blog/entity/Article.java | 17 +-- .../cn/celess/blog/entity/ArticleTag.java | 27 ++++ .../cn/celess/blog/mapper/ArticleMapper.java | 20 +-- .../celess/blog/mapper/ArticleTagMapper.java | 31 +++++ src/main/resources/mapper/articleMapper.xml | 2 +- .../celess/blog/mapper/ArticleMapperTest.java | 75 ++++++++++- .../blog/mapper/ArticleTagMapperTest.java | 126 ++++++++++++++++++ 7 files changed, 257 insertions(+), 41 deletions(-) create mode 100644 src/main/java/cn/celess/blog/entity/ArticleTag.java create mode 100644 src/main/java/cn/celess/blog/mapper/ArticleTagMapper.java create mode 100644 src/test/java/cn/celess/blog/mapper/ArticleTagMapperTest.java diff --git a/src/main/java/cn/celess/blog/entity/Article.java b/src/main/java/cn/celess/blog/entity/Article.java index 496a1d3..e3f3e47 100644 --- a/src/main/java/cn/celess/blog/entity/Article.java +++ b/src/main/java/cn/celess/blog/entity/Article.java @@ -42,21 +42,6 @@ public class Article { private Date updateDate = null; - @Deprecated - private Long categoryId; - - @Deprecated - private String tagsId; - - @Deprecated - private Long authorId; - - @Deprecated - private Long preArticleId; - - @Deprecated - private Long nextArticleId; - private Long readingNumber; /** @@ -73,4 +58,6 @@ public class Article { private Integer dislikeCount; private User user; + + private boolean deleted = false; } diff --git a/src/main/java/cn/celess/blog/entity/ArticleTag.java b/src/main/java/cn/celess/blog/entity/ArticleTag.java new file mode 100644 index 0000000..af8f5d3 --- /dev/null +++ b/src/main/java/cn/celess/blog/entity/ArticleTag.java @@ -0,0 +1,27 @@ +package cn.celess.blog.entity; + +import com.sun.xml.internal.ws.policy.EffectiveAlternativeSelector; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @Author: 小海 + * @Date: 2020-05-24 14:52 + * @Desc: + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class ArticleTag { + private Long id; + + private Article article; + + private TagCategory tag; + + public ArticleTag(Article article, TagCategory tag) { + this.article = article; + this.tag = tag; + } +} diff --git a/src/main/java/cn/celess/blog/mapper/ArticleMapper.java b/src/main/java/cn/celess/blog/mapper/ArticleMapper.java index c5b6e1d..e276fe7 100644 --- a/src/main/java/cn/celess/blog/mapper/ArticleMapper.java +++ b/src/main/java/cn/celess/blog/mapper/ArticleMapper.java @@ -21,15 +21,6 @@ public interface ArticleMapper { int update(Article a); - @Deprecated - int updateNextArticleId(long targetArticleID, long nextArticleID); - - @Deprecated - int updatePreArticleId(long targetArticleID, long preArticleID); - - @Deprecated - long getLastestArticleId(); - Article getLastestArticle(); Article findArticleById(long id); @@ -38,7 +29,7 @@ public interface ArticleMapper { boolean isDeletedById(long id); - List
findAllByAuthorId(long authorID); + List
findAllByAuthorId(long authorId); List
findAllByOpen(boolean isOpen); @@ -48,15 +39,6 @@ public interface ArticleMapper { List
findAll(); - Article getSimpleInfo(long id); - - List
getSimpleInfoByCategory(long categoryId); - - List
getSimpleInfoByTag(List idList); - - @Deprecated - int setReadingNumber(long number, long id); - int updateReadingNumber(long id); long count(); diff --git a/src/main/java/cn/celess/blog/mapper/ArticleTagMapper.java b/src/main/java/cn/celess/blog/mapper/ArticleTagMapper.java new file mode 100644 index 0000000..7991a55 --- /dev/null +++ b/src/main/java/cn/celess/blog/mapper/ArticleTagMapper.java @@ -0,0 +1,31 @@ +package cn.celess.blog.mapper; + +import cn.celess.blog.entity.ArticleTag; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * @Author: 小海 + * @Date: 2020-05-24 14:21 + * @Desc: + */ +@Mapper +@Repository +public interface ArticleTagMapper { + + int insert(ArticleTag articleTag); + + int update(ArticleTag articleTag); + + ArticleTag findOneById(Long id); + + int deleteById(Long id); + + int deleteByArticleId(Long articleId); + + List findAllByArticleId(Long articleId); + + int deleteMultiById(List articleTags); +} diff --git a/src/main/resources/mapper/articleMapper.xml b/src/main/resources/mapper/articleMapper.xml index 7dc1e18..19fc2c9 100644 --- a/src/main/resources/mapper/articleMapper.xml +++ b/src/main/resources/mapper/articleMapper.xml @@ -113,7 +113,7 @@ diff --git a/src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java b/src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java index 1275e91..5a7921a 100644 --- a/src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java +++ b/src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java @@ -20,7 +20,6 @@ public class ArticleMapperTest extends BaseTest { @Test public void insert() { - Article article = generateArticle().getArticle(); assertNotNull(article.getId()); } @@ -33,8 +32,6 @@ public class ArticleMapperTest extends BaseTest { assertFalse(articleMapper.isDeletedById(article.getId())); assertEquals(1, articleMapper.delete(article.getId())); assertTrue(articleMapper.isDeletedById(article.getId())); - - } @Test @@ -88,7 +85,6 @@ public class ArticleMapperTest extends BaseTest { }); } - @Test public void updateReadCount() { Article article = generateArticle().getArticle(); @@ -99,7 +95,6 @@ public class ArticleMapperTest extends BaseTest { assertEquals(Long.valueOf(1), articleById.getReadingNumber()); } - @Test public void getLastestArticle() { Article article = generateArticle().getArticle(); @@ -110,6 +105,73 @@ public class ArticleMapperTest extends BaseTest { assertNotEquals(0, lastestArticle.getTags().size()); } + @Test + public void findArticleById() { + Article article = generateArticle().getArticle(); + Article articleById = articleMapper.findArticleById(article.getId()); + assertNotNull(articleById); + assertEquals(article.getId(), articleById.getId()); + } + + @Test + public void existsByTitle() { + Article article = generateArticle().getArticle(); + assertTrue(articleMapper.existsByTitle(article.getTitle())); + assertFalse(articleMapper.existsByTitle(UUID.randomUUID().toString())); + } + + @Test + public void isDeletedById() { + Article article = generateArticle().getArticle(); + assertFalse(articleMapper.isDeletedById(article.getId())); + articleMapper.delete(article.getId()); + assertTrue(articleMapper.isDeletedById(article.getId())); + + } + + @Test + public void findAllByAuthorId() { + List
allByAuthorId = articleMapper.findAllByAuthorId(1); + assertNotEquals(0, allByAuthorId.size()); + } + + @Test + public void findAllByOpen() { + List
allByOpen = articleMapper.findAllByOpen(true); + assertNotEquals(0, allByOpen); + + Article article = generateArticle().getArticle(); + article.setOpen(false); + + articleMapper.update(article); + + List
privateArticles = articleMapper.findAllByOpen(false); + assertTrue(privateArticles.size() > 0); + } + + @Test + public void getTitleById() { + Article article = generateArticle().getArticle(); + + assertEquals(article.getTitle(), articleMapper.getTitleById(article.getId())); + } + + @Test + public void findAllByCategoryId() { + List
allByCategoryId = articleMapper.findAllByCategoryId(1); + assertNotEquals(0, allByCategoryId.size()); + } + + @Test + public void findAll() { + List
allByCategoryId = articleMapper.findAll(); + assertNotEquals(0, allByCategoryId.size()); + } + + @Test + public void count() { + assertNotEquals(0, articleMapper.count()); + } private ArticleTag generateArticle() { String randomText = UUID.randomUUID().toString(); @@ -122,7 +184,7 @@ public class ArticleMapperTest extends BaseTest { article.setMdContent("# unity test for article"); article.setSummary("unity test for article"); - Tag tag = tagMapper.findTagByName("随笔"); + Tag tag = tagMapper.findTagByName("随笔"); User user = new User(); user.setId(1L); article.setUser(user); @@ -137,4 +199,5 @@ public class ArticleMapperTest extends BaseTest { return articleTag; } + } \ No newline at end of file diff --git a/src/test/java/cn/celess/blog/mapper/ArticleTagMapperTest.java b/src/test/java/cn/celess/blog/mapper/ArticleTagMapperTest.java new file mode 100644 index 0000000..115d90c --- /dev/null +++ b/src/test/java/cn/celess/blog/mapper/ArticleTagMapperTest.java @@ -0,0 +1,126 @@ +package cn.celess.blog.mapper; + +import cn.celess.blog.BaseTest; +import cn.celess.blog.entity.*; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.Iterator; +import java.util.List; +import java.util.UUID; + +import static org.junit.Assert.*; + +public class ArticleTagMapperTest extends BaseTest { + + @Autowired + ArticleMapper articleMapper; + @Autowired + ArticleTagMapper articleTagMapper; + @Autowired + TagMapper tagMapper; + + + @Test + public void insert() { + ArticleTag articleTag = generateArticle(); + assertNotNull(articleTag); + assertNotNull(articleTag.getArticle()); + assertNotNull(articleTag.getTag()); + } + + @Test + public void update() { + Tag tag = tagMapper.findTagByName("电影"); + ArticleTag articleTag = generateArticle(); + articleTag.setTag(tag); + + articleTagMapper.update(articleTag); + + ArticleTag oneById = articleTagMapper.findOneById(articleTag.getId()); + assertEquals(articleTag.getArticle().getId(), oneById.getArticle().getId()); + assertEquals(articleTag.getArticle().getTitle(), oneById.getArticle().getTitle()); + assertEquals(articleTag.getTag().getName(), oneById.getTag().getName()); + } + + @Test + public void deleteById() { + ArticleTag articleTag = generateArticle(); + + articleTagMapper.deleteById(articleTag.getId()); + + ArticleTag oneById = articleTagMapper.findOneById(articleTag.getId()); + assertNull(oneById); + + articleTagMapper.insert(articleTag); + } + + @Test + public void deleteByArticleId() { + ArticleTag articleTag = generateArticle(); + int i = articleTagMapper.deleteByArticleId(articleTag.getArticle().getId()); + assertNotEquals(0, i); + } + + @Test + public void findAllByArticleId() { + ArticleTag articleTag = generateArticle(); + List allByArticleId = articleTagMapper.findAllByArticleId(articleTag.getArticle().getId()); + assertEquals(1, allByArticleId.size()); + + List list = articleTagMapper.findAllByArticleId(5L); + assertEquals(2, list.size()); + } + + @Test + public void deleteMultiById() { + ArticleTag articleTag = new ArticleTag(); + Article article = new Article(); + article.setId(-1L); + Tag tag = new Tag(); + tag.setId(1L); + articleTag.setArticle(article); + articleTag.setTag(tag); + + articleTagMapper.insert(articleTag); + articleTagMapper.insert(articleTag); + articleTagMapper.insert(articleTag); + articleTagMapper.insert(articleTag); + articleTagMapper.insert(articleTag); + articleTagMapper.insert(articleTag); + + List allByArticleId = articleTagMapper.findAllByArticleId(-1L); + assertEquals(6, allByArticleId.size()); + int lines = articleTagMapper.deleteMultiById(allByArticleId); + assertEquals(6, lines); + } + + + private ArticleTag generateArticle() { + String randomText = UUID.randomUUID().toString(); + + Article article = new Article(); + Category category = new Category(); + category.setId(1L); + article.setCategory(category); + article.setTitle(" unity test for article " + randomText); + article.setMdContent("# unity test for article"); + article.setSummary("unity test for article"); + + User user = new User(); + user.setId(1L); + article.setUser(user); + article.setType(true); + + articleMapper.insert(article); + + ArticleTag articleTag = new ArticleTag(); + Tag tag = tagMapper.findTagByName("随笔"); + articleTag.setArticle(article); + articleTag.setTag(tag); + articleTagMapper.insert(articleTag); + + return articleTag; + } + +} \ No newline at end of file From 0136435a41a8024ce00b5ce49e6f421d846b10b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Sun, 24 May 2020 22:02:41 +0800 Subject: [PATCH 05/33] =?UTF-8?q?dao=E5=B1=82=E4=BF=AE=E6=94=B9=20=20?= =?UTF-8?q?=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- newBlog.sql | 1 - .../resources/mapper/ArticleTagMapper.xml | 76 +++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 src/main/resources/mapper/ArticleTagMapper.xml diff --git a/newBlog.sql b/newBlog.sql index 7fc4317..bfaaafd 100644 --- a/newBlog.sql +++ b/newBlog.sql @@ -35,7 +35,6 @@ CREATE TABLE `tag_category` `t_id` bigint(20) primary key auto_increment, `t_name` varchar(255) not null, `is_category` boolean not null default true, - `is_delete` boolean not null default false comment '该数据是否被删除' ) comment '标签和分类表'; CREATE TABLE `comment` diff --git a/src/main/resources/mapper/ArticleTagMapper.xml b/src/main/resources/mapper/ArticleTagMapper.xml new file mode 100644 index 0000000..b8458e1 --- /dev/null +++ b/src/main/resources/mapper/ArticleTagMapper.xml @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + insert into article_tag(a_id, t_id) + values (#{article.id}, #{tag.id}) + + + + + update article_tag + + + a_id = #{article.id}, + + + t_id = #{tag.id}, + + + where at_id = #{tag.id} + + + + + delete + from article_tag + where at_id = #{id}; + + + + delete from article_tag where at_id in + + (#{articleTag.id}) + + + + + + delete + from article_tag + where a_id = #{id} + + + + + + + + \ No newline at end of file From 4f63f7b3d53651392f4ffc7a9e45137813e0cbfd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Sun, 24 May 2020 22:54:51 +0800 Subject: [PATCH 06/33] =?UTF-8?q?dao=E5=B1=82=E4=BF=AE=E6=94=B9=20=20?= =?UTF-8?q?=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/cn/celess/blog/entity/Category.java | 34 +++-- src/main/java/cn/celess/blog/entity/Tag.java | 31 +++-- .../cn/celess/blog/entity/TagCategory.java | 19 +++ .../cn/celess/blog/mapper/CategoryMapper.java | 2 +- .../java/cn/celess/blog/mapper/TagMapper.java | 4 - src/main/resources/mapper/CategoryMapper.xml | 5 +- src/main/resources/mapper/tagMapper.xml | 1 - .../blog/mapper/CategoryMapperTest.java | 119 ++++++++++++++++++ .../cn/celess/blog/mapper/TagMapperTest.java | 91 ++++++++++++++ 9 files changed, 262 insertions(+), 44 deletions(-) create mode 100644 src/main/java/cn/celess/blog/entity/TagCategory.java create mode 100644 src/test/java/cn/celess/blog/mapper/CategoryMapperTest.java create mode 100644 src/test/java/cn/celess/blog/mapper/TagMapperTest.java diff --git a/src/main/java/cn/celess/blog/entity/Category.java b/src/main/java/cn/celess/blog/entity/Category.java index b72c9a0..815f7aa 100644 --- a/src/main/java/cn/celess/blog/entity/Category.java +++ b/src/main/java/cn/celess/blog/entity/Category.java @@ -1,20 +1,14 @@ -package cn.celess.blog.entity; - - -import lombok.Data; - - -/** - * @author : xiaohai - * @date : 2019/03/28 22:18 - */ -@Data -public class Category { - - private Long id; - - private String name; - - private String articles; - -} +package cn.celess.blog.entity; + +import lombok.NoArgsConstructor; + +/** + * @author : xiaohai + * @date : 2019/03/28 22:18 + */ +@NoArgsConstructor +public class Category extends TagCategory { + public Category(String name) { + super.setName(name); + } +} diff --git a/src/main/java/cn/celess/blog/entity/Tag.java b/src/main/java/cn/celess/blog/entity/Tag.java index 58526a4..e120cd0 100644 --- a/src/main/java/cn/celess/blog/entity/Tag.java +++ b/src/main/java/cn/celess/blog/entity/Tag.java @@ -1,16 +1,15 @@ -package cn.celess.blog.entity; - -import lombok.Data; - -/** - * @author : xiaohai - * @date : 2019/03/28 22:19 - */ -@Data -public class Tag { - private Long id; - - private String name; - - private String articles; -} +package cn.celess.blog.entity; + +import lombok.NoArgsConstructor; + +/** + * @author : xiaohai + * @date : 2019/03/28 22:19 + */ +@NoArgsConstructor +public class Tag extends TagCategory { + + public Tag(String name) { + super.setName(name); + } +} diff --git a/src/main/java/cn/celess/blog/entity/TagCategory.java b/src/main/java/cn/celess/blog/entity/TagCategory.java new file mode 100644 index 0000000..e8c0a16 --- /dev/null +++ b/src/main/java/cn/celess/blog/entity/TagCategory.java @@ -0,0 +1,19 @@ +package cn.celess.blog.entity; + +import lombok.Data; + +/** + * @Author: 小海 + * @Date: 2020-05-24 14:03 + * @Desc: + */ +@Data +public class TagCategory { + private Long id; + + private String name; + + private boolean category = true; + + private boolean deleted = false; +} diff --git a/src/main/java/cn/celess/blog/mapper/CategoryMapper.java b/src/main/java/cn/celess/blog/mapper/CategoryMapper.java index 2c3f941..2fc9017 100644 --- a/src/main/java/cn/celess/blog/mapper/CategoryMapper.java +++ b/src/main/java/cn/celess/blog/mapper/CategoryMapper.java @@ -34,7 +34,7 @@ public interface CategoryMapper { String getNameById(long id); - Long getIDByName(String name); + Long getIdByName(String name); Category getLastestCategory(); diff --git a/src/main/java/cn/celess/blog/mapper/TagMapper.java b/src/main/java/cn/celess/blog/mapper/TagMapper.java index 4877747..ed479c9 100644 --- a/src/main/java/cn/celess/blog/mapper/TagMapper.java +++ b/src/main/java/cn/celess/blog/mapper/TagMapper.java @@ -26,10 +26,6 @@ public interface TagMapper { Boolean existsByName(String name); - Long getIDByName(String name); - - String getNameById(long id); - Tag getLastestTag(); List findAll(); diff --git a/src/main/resources/mapper/CategoryMapper.xml b/src/main/resources/mapper/CategoryMapper.xml index 38d06fc..21363ea 100644 --- a/src/main/resources/mapper/CategoryMapper.xml +++ b/src/main/resources/mapper/CategoryMapper.xml @@ -1,7 +1,7 @@ - + @@ -56,7 +56,8 @@ - select EXISTS(select * from web_update where update_id = #{id}) + select EXISTS(select * from web_update where wu_id = #{id}) + + + + diff --git a/src/test/java/cn/celess/blog/mapper/WebUpdateInfoMapperTest.java b/src/test/java/cn/celess/blog/mapper/WebUpdateInfoMapperTest.java new file mode 100644 index 0000000..2ddd107 --- /dev/null +++ b/src/test/java/cn/celess/blog/mapper/WebUpdateInfoMapperTest.java @@ -0,0 +1,80 @@ +package cn.celess.blog.mapper; + +import cn.celess.blog.BaseTest; +import cn.celess.blog.entity.WebUpdate; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.List; + +import static org.junit.Assert.*; + +public class WebUpdateInfoMapperTest extends BaseTest { + + @Autowired + WebUpdateInfoMapper webUpdateInfoMapper; + + @Test + public void insert() { + WebUpdate webUpdate = generateUpdateInfo(); + assertNotNull(webUpdate); + } + + @Test + public void delete() { + WebUpdate webUpdate = generateUpdateInfo(); + assertEquals(1, webUpdateInfoMapper.delete(webUpdate.getId())); + assertTrue(webUpdateInfoMapper.findById(webUpdate.getId()).isDelete()); + } + + @Test + public void update() { + WebUpdate webUpdate = generateUpdateInfo(); + assertEquals(1, webUpdateInfoMapper.update(webUpdate.getId(), randomStr(6))); + } + + @Test + public void existsById() { + WebUpdate webUpdate = generateUpdateInfo(); + assertTrue(webUpdateInfoMapper.existsById(webUpdate.getId())); + } + + @Test + public void findById() { + WebUpdate webUpdate = generateUpdateInfo(); + WebUpdate byId = webUpdateInfoMapper.findById(webUpdate.getId()); + assertEquals(webUpdate.getUpdateInfo(), byId.getUpdateInfo()); + assertEquals(webUpdate.getId(), byId.getId()); + } + + @Test + public void findAll() { + List all = webUpdateInfoMapper.findAll(); + assertNotEquals(0, all.size()); + } + + @Test + public void findAllNotDeleted() { + this.delete(); + List allNotDeleted = webUpdateInfoMapper.findAllNotDeleted(); + allNotDeleted.forEach(webUpdate -> assertFalse(webUpdate.isDelete())); + } + + @Test + public void getLastestOne() { + WebUpdate webUpdate = generateUpdateInfo(); + List all = webUpdateInfoMapper.findAll(); + List allNotDeleted = webUpdateInfoMapper.findAllNotDeleted(); + all.sort(((o1, o2) -> (int) (o2.getId() - o1.getId()))); + allNotDeleted.sort(((o1, o2) -> (int) (o2.getId() - o1.getId()))); + assertEquals(webUpdate.getId(), all.get(0).getId()); + assertEquals(webUpdate.getId(), allNotDeleted.get(0).getId()); + assertEquals(webUpdate.getId(), webUpdateInfoMapper.getLastestOne().getId()); + } + + private WebUpdate generateUpdateInfo() { + WebUpdate webUpdate = new WebUpdate(randomStr(8)); + webUpdateInfoMapper.insert(webUpdate); + return webUpdate; + } +} \ No newline at end of file From 86b6bae6e6b562203b2033db026f2deaea1d5511 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Mon, 25 May 2020 00:02:26 +0800 Subject: [PATCH 08/33] =?UTF-8?q?dao=E5=B1=82=E4=BF=AE=E6=94=B9=20=20?= =?UTF-8?q?=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/cn/celess/blog/entity/Visitor.java | 1 + .../cn/celess/blog/mapper/VisitorMapper.java | 2 + .../celess/blog/mapper/VisitorMapperTest.java | 42 +++++++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 src/test/java/cn/celess/blog/mapper/VisitorMapperTest.java diff --git a/src/main/java/cn/celess/blog/entity/Visitor.java b/src/main/java/cn/celess/blog/entity/Visitor.java index 2092745..5767cf1 100644 --- a/src/main/java/cn/celess/blog/entity/Visitor.java +++ b/src/main/java/cn/celess/blog/entity/Visitor.java @@ -15,6 +15,7 @@ public class Visitor { private String ip; private Date date; private String ua; + private boolean delete; public Visitor(String ip, Date date, String ua) { this.ip = ip; diff --git a/src/main/java/cn/celess/blog/mapper/VisitorMapper.java b/src/main/java/cn/celess/blog/mapper/VisitorMapper.java index ed84320..e47a661 100644 --- a/src/main/java/cn/celess/blog/mapper/VisitorMapper.java +++ b/src/main/java/cn/celess/blog/mapper/VisitorMapper.java @@ -20,5 +20,7 @@ public interface VisitorMapper { List findAll(); + List findAllNotDeleted(); + long count(); } diff --git a/src/test/java/cn/celess/blog/mapper/VisitorMapperTest.java b/src/test/java/cn/celess/blog/mapper/VisitorMapperTest.java new file mode 100644 index 0000000..d782c94 --- /dev/null +++ b/src/test/java/cn/celess/blog/mapper/VisitorMapperTest.java @@ -0,0 +1,42 @@ +package cn.celess.blog.mapper; + +import cn.celess.blog.BaseTest; +import cn.celess.blog.entity.Visitor; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.Date; + +import static org.junit.Assert.*; + +public class VisitorMapperTest extends BaseTest { + + @Autowired + VisitorMapper visitorMapper; + + @Test + public void insert() { + Visitor visitor = new Visitor(); + visitor.setDate(new Date()); + visitor.setIp("127.0.0.1"); + visitor.setUa("ua"); + assertEquals(1, visitorMapper.insert(visitor)); + } + + @Test + public void delete() { + Visitor visitor = new Visitor(); + visitor.setDate(new Date()); + visitor.setIp("127.0.0.1"); + visitor.setUa("ua"); + visitorMapper.insert(visitor); + assertEquals(1, visitorMapper.delete(visitor.getId())); + } + + @Test + public void count() { + assertNotEquals(0, visitorMapper.count()); + } + + +} \ No newline at end of file From 190e1624ca1ec3d1efe185e6a9329e36c04706a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Mon, 25 May 2020 00:20:36 +0800 Subject: [PATCH 09/33] =?UTF-8?q?dao=E5=B1=82=E4=BF=AE=E6=94=B9=20=20?= =?UTF-8?q?=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cn/celess/blog/entity/PartnerSite.java | 6 + .../resources/mapper/PartnerSiteMapper.xml | 54 ++++----- src/main/resources/mapper/VisitorMapper.xml | 24 ++-- .../celess/blog/mapper/PartnerMapperTest.java | 103 ++++++++++++++++++ 4 files changed, 152 insertions(+), 35 deletions(-) create mode 100644 src/test/java/cn/celess/blog/mapper/PartnerMapperTest.java diff --git a/src/main/java/cn/celess/blog/entity/PartnerSite.java b/src/main/java/cn/celess/blog/entity/PartnerSite.java index c1a1493..40ae597 100644 --- a/src/main/java/cn/celess/blog/entity/PartnerSite.java +++ b/src/main/java/cn/celess/blog/entity/PartnerSite.java @@ -19,6 +19,12 @@ public class PartnerSite { private Boolean open; + private String iconPath; + + private String desc; + + private boolean delete; + public PartnerSite() { } diff --git a/src/main/resources/mapper/PartnerSiteMapper.xml b/src/main/resources/mapper/PartnerSiteMapper.xml index 563521d..f3be559 100644 --- a/src/main/resources/mapper/PartnerSiteMapper.xml +++ b/src/main/resources/mapper/PartnerSiteMapper.xml @@ -2,69 +2,71 @@ - - - - + + + + + + + - - insert into links (site_name, is_open, site_url) - values (#{name}, #{open}, #{url}) - - SELECT LAST_INSERT_ID() AS id - + + insert into links (l_name, l_is_open, l_url, l_icon_path, l_desc, is_delete) + values (#{name}, #{open}, #{url}, #{iconPath}, #{desc}, false) update links set - site_name=#{name}, - site_url=#{url}, - is_open=#{open} - where site_id=#{id} + l_name=#{name}, + l_url=#{url}, + l_is_open=#{open}, + l_icon_path=#{iconPath}, + l_desc=#{desc} + where l_id=#{id} - - delete - from links - where site_id = #{id} - + + update links + set is_delete = true + where l_id = #{id} + select * - from visitor order by v_id desc + from visitor + order by v_id desc + + + SELECT EXISTS(SELECT * FROM comment WHERE co_id = #{id}) - select * - from comment - where co_id = #{id} + from commentView + where commentId = #{id} - select * - from comment - where author_id = #{id} - and is_comment = #{isComment} + from commentView + where fromAuthorId = #{id} - select * - from comment - where co_pid = #{pid} + from commentView + where pid = #{pid} - select * - from comment - where co_article_id = #{articleId} + from commentView + where pagePath = #{pagePath} - select * - from comment - where co_article_id = #{articleID} - and co_pid = #{pid} + from commentView + where pagePath = #{pagePath} + and pid = #{pid} - - - select count(*) - from comment - where is_comment = #{isComment} + from commentView + where pagePath = #{pagePath} - select * - from comment - order by co_id desc + from commentView + order by commentId desc limit 1 diff --git a/src/test/java/cn/celess/blog/mapper/CommentMapperTest.java b/src/test/java/cn/celess/blog/mapper/CommentMapperTest.java new file mode 100644 index 0000000..3c78167 --- /dev/null +++ b/src/test/java/cn/celess/blog/mapper/CommentMapperTest.java @@ -0,0 +1,132 @@ +package cn.celess.blog.mapper; + +import cn.celess.blog.BaseTest; +import cn.celess.blog.entity.Comment; +import cn.celess.blog.entity.User; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.List; + +import static org.junit.Assert.*; + +public class CommentMapperTest extends BaseTest { + + @Autowired + UserMapper userMapper; + @Autowired + CommentMapper commentMapper; + + @Test + public void insert() { + Comment comment = generateComment(); + assertNotNull(comment.getId()); + } + + @Test + public void updateContent() { + Comment comment = generateComment(); + comment.setContent(randomStr(10)); + assertEquals(1, commentMapper.updateContent(comment.getContent(), comment.getId())); + } + + @Test + public void delete() { + Comment comment = generateComment(); + assertEquals(1, commentMapper.delete(comment.getId())); + Comment commentById = commentMapper.findCommentById(comment.getId()); + assertTrue(commentById.isDelete()); + } + + @Test + public void deleteByPagePath() { + Comment comment = generateComment(); + assertTrue(commentMapper.deleteByPagePath(comment.getPagePath()) >= 1); + Comment commentById = commentMapper.findCommentById(comment.getId()); + assertTrue(commentById.isDelete()); + } + + @Test + public void existsById() { + Comment comment = generateComment(); + assertTrue(commentMapper.existsById(comment.getId())); + } + + @Test + public void findCommentById() { + Comment comment = generateComment(); + assertNotNull(commentMapper.findCommentById(comment.getId())); + } + + @Test + public void getLastestComment() { + Comment comment = generateComment(); + Comment lastestComment = commentMapper.getLastestComment(); + assertEquals(comment.getId(), lastestComment.getId()); + } + + @Test + public void findAllByFromUser() { + Comment comment = generateComment(); + List allByFromUser = commentMapper.findAllByFromUser(comment.getFromUser().getId()); + assertNotEquals(0, allByFromUser); + allByFromUser.forEach(comment1 -> assertEquals(comment.getFromUser().getId(), comment1.getFromUser().getId())); + } + + @Test + public void findAllByPid() { + Comment comment = generateComment(); + List allByPid = commentMapper.findAllByPid(comment.getPid()); + assertTrue(allByPid.size() >= 1); + } + + @Test + public void findAllByPagePath() { + Comment comment = generateComment(); + List allByPagePath = commentMapper.findAllByPagePath(comment.getPagePath()); + assertTrue(allByPagePath.size() >= 1); + allByPagePath.forEach(comment1 -> assertEquals(comment.getPagePath(), comment1.getPagePath())); + } + + @Test + public void findAllByPagePathAndPid() { + Comment comment = generateComment(); + List allByPagePathAndPid = commentMapper.findAllByPagePathAndPid(comment.getPagePath(), comment.getPid()); + assertTrue(allByPagePathAndPid.size() >= 1); + allByPagePathAndPid.forEach(comment1 -> { + assertEquals(comment.getPagePath(), comment1.getPagePath()); + assertEquals(comment.getPid(), comment1.getPid()); + }); + } + + @Test + public void testFindAllByPid() { + Comment comment = generateComment(); + List findAllByPid = commentMapper.findAllByPid(comment.getPid()); + assertTrue(findAllByPid.size() >= 1); + findAllByPid.forEach(comment1 -> assertEquals(comment.getPid(), comment1.getPid())); + } + + @Test + public void countByType() { + Comment comment = generateComment(); + long l = commentMapper.countByPagePath(comment.getPagePath()); + assertTrue(l >= 1); + } + + private Comment generateComment() { + User from = userMapper.findById(1); + assertNotNull(from); + User to = userMapper.findById(2); + assertNotNull(to); + + Comment comment = new Comment(); + comment.setContent(randomStr(8)); + comment.setFromUser(from); + comment.setToUser(to); + comment.setPagePath("/tags"); + comment.setPid(-1L); + commentMapper.insert(comment); + return comment; + } +} \ No newline at end of file From 9e6868b638299a90e10142a13395d0956ae61b4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Mon, 25 May 2020 14:48:05 +0800 Subject: [PATCH 11/33] =?UTF-8?q?dao=E5=B1=82=E4=BF=AE=E6=94=B9=20=20?= =?UTF-8?q?=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../celess/blog/enmu/CommentStatusEnum.java | 17 ++ .../java/cn/celess/blog/enmu/RoleEnum.java | 23 +++ .../java/cn/celess/blog/entity/Comment.java | 16 +- src/main/java/cn/celess/blog/entity/User.java | 21 +- .../cn/celess/blog/mapper/UserMapper.java | 8 +- src/main/resources/mapper/UserMapper.xml | 74 +++---- .../cn/celess/blog/mapper/UserMapperTest.java | 185 ++++++++++++++++++ 7 files changed, 282 insertions(+), 62 deletions(-) create mode 100644 src/main/java/cn/celess/blog/enmu/CommentStatusEnum.java create mode 100644 src/main/java/cn/celess/blog/enmu/RoleEnum.java create mode 100644 src/test/java/cn/celess/blog/mapper/UserMapperTest.java diff --git a/src/main/java/cn/celess/blog/enmu/CommentStatusEnum.java b/src/main/java/cn/celess/blog/enmu/CommentStatusEnum.java new file mode 100644 index 0000000..84ac6bc --- /dev/null +++ b/src/main/java/cn/celess/blog/enmu/CommentStatusEnum.java @@ -0,0 +1,17 @@ +package cn.celess.blog.enmu; + +import com.sun.javaws.jnl.IconDesc; + +/** + * @Author: 小海 + * @Date: 2020-05-25 08:58 + * @Desc: + */ +public enum CommentStatusEnum { + // 正常 + NORMAL(0, "正常"); + + + CommentStatusEnum(int code, String msg) { + } +} diff --git a/src/main/java/cn/celess/blog/enmu/RoleEnum.java b/src/main/java/cn/celess/blog/enmu/RoleEnum.java new file mode 100644 index 0000000..8f399f2 --- /dev/null +++ b/src/main/java/cn/celess/blog/enmu/RoleEnum.java @@ -0,0 +1,23 @@ +package cn.celess.blog.enmu; + +import lombok.Getter; + +/** + * @Author: 小海 + * @Date: 2020-05-24 16:31 + * @Desc: + */ +@Getter +public enum RoleEnum { + // admin 权限 + ADMIN_ROLE("admin"), + // user 权限 + USER_ROLE("user"); + + + private final String roleName; + + RoleEnum(String roleName) { + this.roleName = roleName; + } +} diff --git a/src/main/java/cn/celess/blog/entity/Comment.java b/src/main/java/cn/celess/blog/entity/Comment.java index 90b480f..03ce756 100644 --- a/src/main/java/cn/celess/blog/entity/Comment.java +++ b/src/main/java/cn/celess/blog/entity/Comment.java @@ -14,27 +14,21 @@ public class Comment { private Long id; - /** - * 是评论还是留言 0:评论 其他(1):留言 - */ - private Boolean type; + private int status; - private Long authorID; + private String pagePath; private String content; - private Long articleID; - private Date date; - /** - * 回应着ID 默认为顶级回复 - */ - private String responseId = ""; + private User fromUser; + private User toUser; /** * 评论的父ID */ private Long pid; + private boolean delete; } diff --git a/src/main/java/cn/celess/blog/entity/User.java b/src/main/java/cn/celess/blog/entity/User.java index 7a3d9dd..f912025 100644 --- a/src/main/java/cn/celess/blog/entity/User.java +++ b/src/main/java/cn/celess/blog/entity/User.java @@ -2,6 +2,7 @@ package cn.celess.blog.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; +import lombok.NoArgsConstructor; import java.util.Date; @@ -10,6 +11,7 @@ import java.util.Date; * @date : 2019/03/28 14:52 */ @Data +@NoArgsConstructor public class User { private Long id; @@ -18,12 +20,6 @@ public class User { */ private String email; - /** - * 用户唯一标识码 - */ - @JsonIgnore - private String uid; - /** * 密码 */ @@ -46,15 +42,12 @@ public class User { private Date recentlyLandedDate; - /** - * 随机码 用户验证邮箱/找回密码 - * 暂时废弃这一字段 - */ - private String emailVerifyId; - private String role = "user"; - public User() { - } + private int status; + public User(String email, String pwd) { + this.email = email; + this.pwd = pwd; + } } diff --git a/src/main/java/cn/celess/blog/mapper/UserMapper.java b/src/main/java/cn/celess/blog/mapper/UserMapper.java index 6419da4..2b83e76 100644 --- a/src/main/java/cn/celess/blog/mapper/UserMapper.java +++ b/src/main/java/cn/celess/blog/mapper/UserMapper.java @@ -16,13 +16,13 @@ import java.util.List; @Repository public interface UserMapper { - int addUser(String email, String pwd); + int addUser(User user); int updateInfo(String desc, String displayName, long id); int updateAvatarImgUrl(String avatarImgUrl, long id); - int updateLoginTime(String email, Date date); + int updateLoginTime(String email); int updateEmailStatus(String email, boolean status); @@ -50,7 +50,9 @@ public interface UserMapper { int delete(long id); - int setUserRole(Long uid, String role); + int lock(long id); + + int setUserRole(Long id, String role); List findAll(); diff --git a/src/main/resources/mapper/UserMapper.xml b/src/main/resources/mapper/UserMapper.xml index b9888b8..f1f720a 100644 --- a/src/main/resources/mapper/UserMapper.xml +++ b/src/main/resources/mapper/UserMapper.xml @@ -4,68 +4,74 @@ - - + - - - - + + + + - + insert into user(u_email, u_pwd) values (#{email}, #{pwd}) update user set - `u_desc`=#{desc}, - `display_name`=#{displayName} + u_desc=#{desc}, + u_display_name=#{displayName} where u_id=#{id} update user - set `recently_landed_time`=#{date} - where `u_email` = #{email} + set u_recently_landed_time=now() + where u_email = #{email} update user - set `u_avatar`=#{avatarImgUrl} - where `u_id` = #{id} + set u_avatar=#{avatarImgUrl} + where u_id = #{id} update user - set `email_status`=#{status} - where `u_email` = #{email} + set u_email_status=#{status} + where u_email = #{email} update user - set `u_pwd`=#{pwd} - where `u_email` = #{email} + set u_pwd=#{pwd} + where u_email = #{email} update user - set role=#{role} - where u_id = #{uid} + set u_role=#{role} + where u_id = #{id} update user - set `u_email` = #{email}, - `u_pwd` = #{pwd}, - `email_status` = #{emailStatus}, - `u_desc` = #{desc}, - `display_name` = #{displayName}, - `role` = #{role} - where `u_id` = #{id} - - - delete - from user + set u_email = #{email}, + u_pwd = #{pwd}, + u_email_status = #{emailStatus}, + u_desc = #{desc}, + u_display_name = #{displayName}, + u_avatar = #{avatarImgUrl}, + u_role = #{role} where u_id = #{id} - + + + update user + set status= 2 + where u_id = #{id} + + + + update user + set status= 1 + where u_id = #{id} + @@ -107,7 +113,7 @@ where u_email = #{email} @@ -116,7 +122,7 @@ from user diff --git a/src/test/java/cn/celess/blog/mapper/UserMapperTest.java b/src/test/java/cn/celess/blog/mapper/UserMapperTest.java new file mode 100644 index 0000000..0b6e6a3 --- /dev/null +++ b/src/test/java/cn/celess/blog/mapper/UserMapperTest.java @@ -0,0 +1,185 @@ +package cn.celess.blog.mapper; + +import cn.celess.blog.BaseTest; +import cn.celess.blog.enmu.RoleEnum; +import cn.celess.blog.enmu.UserAccountStatusEnum; +import cn.celess.blog.entity.User; +import cn.celess.blog.util.MD5Util; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.List; + +import static org.junit.Assert.*; + +public class UserMapperTest extends BaseTest { + + @Autowired + UserMapper userMapper; + + + @Test + public void addUser() { + User user = generateUser(); + assertNotNull(user.getId()); + } + + @Test + public void updateInfo() { + User user = generateUser(); + assertEquals(1, userMapper.updateInfo("ttt", "ttt", user.getId())); + } + + @Test + public void updateAvatarImgUrl() { + User user = generateUser(); + assertEquals(1, userMapper.updateAvatarImgUrl("https://www.celess.cn/example.jpg", user.getId())); + } + + @Test + public void updateLoginTime() { + User user = generateUser(); + assertEquals(1, userMapper.updateLoginTime(user.getEmail())); + } + + @Test + public void updateEmailStatus() { + User user = generateUser(); + assertEquals(1, userMapper.updateEmailStatus(user.getEmail(), true)); + } + + @Test + public void updatePwd() { + User user = generateUser(); + assertEquals(1, userMapper.updatePwd(user.getEmail(), MD5Util.getMD5("12345687654"))); + } + + @Test + public void getPwd() { + User user = generateUser(); + assertEquals(user.getPwd(), userMapper.getPwd(user.getEmail())); + } + + @Test + public void existsByEmail() { + User user = generateUser(); + assertTrue(userMapper.existsByEmail(user.getEmail())); + } + + @Test + public void findByEmail() { + User user = generateUser(); + User byEmail = userMapper.findByEmail(user.getEmail()); + assertNotNull(byEmail); + assertEquals(user.getId(), byEmail.getId()); + } + + @Test + public void findById() { + User user = generateUser(); + User findById = userMapper.findById(user.getId()); + assertNotNull(findById); + assertEquals(user.getEmail(), findById.getEmail()); + } + + @Test + public void getAvatarImgUrlById() { + User user = generateUser(); + assertNull(userMapper.getAvatarImgUrlById(user.getId())); + userMapper.updateAvatarImgUrl("example.cn", user.getId()); + assertEquals("example.cn", userMapper.getAvatarImgUrlById(user.getId())); + + } + + @Test + public void getEmail() { + User user = generateUser(); + assertEquals(user.getEmail(), userMapper.getEmail(user.getId())); + } + + @Test + public void getDisPlayName() { + User user = generateUser(); + assertNull(userMapper.getDisPlayName(user.getId())); + } + + @Test + public void getRoleByEmail() { + User user = generateUser(); + assertEquals(RoleEnum.USER_ROLE.getRoleName(), userMapper.getRoleByEmail(user.getEmail())); + } + + @Test + public void getRoleById() { + User user = generateUser(); + assertEquals(RoleEnum.USER_ROLE.getRoleName(), userMapper.getRoleById(user.getId())); + } + + @Test + public void count() { + generateUser(); + assertTrue(userMapper.count() >= 1); + } + + @Test + public void delete() { + User user = generateUser(); + int delete = userMapper.delete(user.getId()); + assertEquals(1, delete); + User byId = userMapper.findById(user.getId()); + assertEquals(UserAccountStatusEnum.DELETED.getCode(), byId.getStatus()); + } + + @Test + public void lock() { + User user = generateUser(); + int delete = userMapper.lock(user.getId()); + assertEquals(1, delete); + User byId = userMapper.findById(user.getId()); + assertEquals(UserAccountStatusEnum.LOCKED.getCode(), byId.getStatus()); + } + + @Test + public void setUserRole() { + User user = generateUser(); + userMapper.setUserRole(user.getId(), RoleEnum.ADMIN_ROLE.getRoleName()); + + assertEquals(RoleEnum.ADMIN_ROLE.getRoleName(), userMapper.getRoleById(user.getId())); + } + + @Test + public void findAll() { + User user = generateUser(); + List all = userMapper.findAll(); + assertTrue(all.size() >= 1); + } + + @Test + public void update() { + User user = generateUser(); + user.setDesc("aaa"); + user.setDisplayName("bbb"); + user.setEmailStatus(true); + user.setRole(RoleEnum.ADMIN_ROLE.getRoleName()); + user.setAvatarImgUrl("https://celess.cn/examcple.jpg"); + user.setEmail(randomStr(8) + "@celess.cn"); + user.setPwd(MD5Util.getMD5("010100000100000")); + assertEquals(1, userMapper.update(user)); + User byId = userMapper.findById(user.getId()); + assertEquals(user.getDesc(), byId.getDesc()); + assertEquals(user.getDisplayName(), byId.getDisplayName()); + assertEquals(user.getEmailStatus(), byId.getEmailStatus()); + assertEquals(user.getRole(), byId.getRole()); + assertEquals(user.getAvatarImgUrl(), byId.getAvatarImgUrl()); + assertEquals(user.getEmail(), byId.getEmail()); + assertEquals(user.getPwd(), byId.getPwd()); + } + + private User generateUser() { + User user = new User(randomStr(6) + "@celess.cn", MD5Util.getMD5("1234567890")); + userMapper.addUser(user); + User newUser = userMapper.findByEmail(user.getEmail()); + assertEquals(user.getId(), newUser.getId()); + return newUser; + } +} \ No newline at end of file From 67a1b1faf9aba54520cc7ebd4c7141374dbf5707 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Mon, 25 May 2020 21:43:53 +0800 Subject: [PATCH 12/33] =?UTF-8?q?Service=E5=B1=82=E4=BF=AE=E6=94=B9=20=20?= =?UTF-8?q?=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../blog/controller/ArticleController.java | 4 +- .../blog/entity/model/ArticleModel.java | 30 +- .../cn/celess/blog/entity/model/PageData.java | 38 +++ .../cn/celess/blog/mapper/ArticleMapper.java | 6 + .../celess/blog/mapper/ArticleTagMapper.java | 4 + .../serviceimpl/ArticleServiceImpl.java | 256 ++++++------------ .../java/cn/celess/blog/util/ModalTrans.java | 37 +++ .../resources/mapper/ArticleTagMapper.xml | 28 +- src/main/resources/mapper/articleMapper.xml | 26 ++ .../controller/ArticleControllerTest.java | 97 +++---- .../celess/blog/mapper/ArticleMapperTest.java | 23 +- .../blog/mapper/ArticleTagMapperTest.java | 21 +- 12 files changed, 317 insertions(+), 253 deletions(-) create mode 100644 src/main/java/cn/celess/blog/entity/model/PageData.java create mode 100644 src/main/java/cn/celess/blog/util/ModalTrans.java diff --git a/src/main/java/cn/celess/blog/controller/ArticleController.java b/src/main/java/cn/celess/blog/controller/ArticleController.java index a8177d2..1faf686 100644 --- a/src/main/java/cn/celess/blog/controller/ArticleController.java +++ b/src/main/java/cn/celess/blog/controller/ArticleController.java @@ -80,10 +80,10 @@ public class ArticleController { public Response retrieveOneById(@PathVariable("articleID") long articleId, @RequestParam(value = "update", defaultValue = "false") boolean is4update, HttpServletRequest request) { - ArticleModel article = articleService.retrieveOneByID(articleId, is4update); + ArticleModel article = articleService.retrieveOneById(articleId, is4update); if (article.getOpen()) { return ResponseUtil.success(article); - } else if (article.getAuthorId().equals(redisUserUtil.get().getId())) { + } else if (article.getAuthor().getId().equals(redisUserUtil.get().getId())) { return ResponseUtil.success(article); } return ResponseUtil.response(ResponseEnum.PERMISSION_ERROR, null); diff --git a/src/main/java/cn/celess/blog/entity/model/ArticleModel.java b/src/main/java/cn/celess/blog/entity/model/ArticleModel.java index 22cd274..ed86ab9 100644 --- a/src/main/java/cn/celess/blog/entity/model/ArticleModel.java +++ b/src/main/java/cn/celess/blog/entity/model/ArticleModel.java @@ -1,9 +1,11 @@ package cn.celess.blog.entity.model; +import cn.celess.blog.entity.Tag; import lombok.Getter; import lombok.Setter; import java.io.Serializable; +import java.util.List; /** * @author : xiaohai @@ -57,40 +59,28 @@ public class ArticleModel { /** * 标签 */ - private String[] tags; + private List tags; /** * 作者 */ - private Long authorId; + private UserModel author; - /** - * 作者名字 - */ - private String authorName; + private ArticleModel preArticle; - /** - * 上一篇文章 - */ - private Long preArticleId; - - /** - * 下一篇文章 - */ - private Long nextArticleId; - - private String preArticleTitle; - - private String nextArticleTitle; + private ArticleModel nextArticle; /** * 阅读数 */ private Long readingNumber; + private Integer likeCount; + + private Integer dislikeCount; + /** * 文章的状态 true:公开 false:不公开 */ private Boolean open; - } diff --git a/src/main/java/cn/celess/blog/entity/model/PageData.java b/src/main/java/cn/celess/blog/entity/model/PageData.java new file mode 100644 index 0000000..5e75273 --- /dev/null +++ b/src/main/java/cn/celess/blog/entity/model/PageData.java @@ -0,0 +1,38 @@ +package cn.celess.blog.entity.model; + +import com.github.pagehelper.PageInfo; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +/** + * @Author: 小海 + * @Date: 2020-05-25 17:13 + * @Desc: + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class PageData { + + private List list; + + private long total; + + private int pageSize; + + private int pageNum; + + public PageData(PageInfo pageInfo) { + this.pageNum = pageInfo.getPageNum(); + this.pageSize = pageInfo.getPageSize(); + this.total = pageInfo.getTotal(); + } + + public PageData(PageInfo pageInfo, List data) { + this(pageInfo); + this.list = data; + } +} diff --git a/src/main/java/cn/celess/blog/mapper/ArticleMapper.java b/src/main/java/cn/celess/blog/mapper/ArticleMapper.java index e276fe7..c7b8d49 100644 --- a/src/main/java/cn/celess/blog/mapper/ArticleMapper.java +++ b/src/main/java/cn/celess/blog/mapper/ArticleMapper.java @@ -37,8 +37,14 @@ public interface ArticleMapper { List
findAllByCategoryId(long id); + List
findAllByCategoryIdAndOpen(long id); + List
findAll(); + Article getPreArticle(Long id); + + Article getNextArticle(Long id); + int updateReadingNumber(long id); long count(); diff --git a/src/main/java/cn/celess/blog/mapper/ArticleTagMapper.java b/src/main/java/cn/celess/blog/mapper/ArticleTagMapper.java index 7991a55..bcf4fc7 100644 --- a/src/main/java/cn/celess/blog/mapper/ArticleTagMapper.java +++ b/src/main/java/cn/celess/blog/mapper/ArticleTagMapper.java @@ -28,4 +28,8 @@ public interface ArticleTagMapper { List findAllByArticleId(Long articleId); int deleteMultiById(List articleTags); + + List findArticleByTag(Long tagId); + + List findArticleByTagAndOpen(Long tagId); } diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/ArticleServiceImpl.java b/src/main/java/cn/celess/blog/service/serviceimpl/ArticleServiceImpl.java index 1f2dbab..7a7eeda 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/ArticleServiceImpl.java +++ b/src/main/java/cn/celess/blog/service/serviceimpl/ArticleServiceImpl.java @@ -1,24 +1,21 @@ package cn.celess.blog.service.serviceimpl; -import cn.celess.blog.enmu.LevelEnum; import cn.celess.blog.enmu.ResponseEnum; import cn.celess.blog.enmu.RoleEnum; import cn.celess.blog.entity.*; import cn.celess.blog.entity.model.ArticleModel; +import cn.celess.blog.entity.model.PageData; import cn.celess.blog.entity.request.ArticleReq; import cn.celess.blog.exception.MyException; import cn.celess.blog.mapper.*; import cn.celess.blog.service.ArticleService; import cn.celess.blog.service.UserService; -import cn.celess.blog.util.DateFormatUtil; -import cn.celess.blog.util.RedisUserUtil; -import cn.celess.blog.util.RegexUtil; -import cn.celess.blog.util.StringFromHtmlUtil; +import cn.celess.blog.util.*; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.youbenzi.mdtool.tool.MDTool; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -26,7 +23,6 @@ import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.Arrays; -import java.util.Date; import java.util.List; @@ -35,8 +31,8 @@ import java.util.List; * @date : 2019/03/28 15:21 */ @Service +@Slf4j public class ArticleServiceImpl implements ArticleService { - public static final Logger logger = LoggerFactory.getLogger(ArticleServiceImpl.class); @Autowired ArticleMapper articleMapper; @@ -86,22 +82,16 @@ public class ArticleServiceImpl implements ArticleService { throw new MyException(ResponseEnum.ARTICLE_HAS_EXIST); } // 查看是否存在已有的分类 - Category category = (Category) categoryMapper.findCategoryByName(reqBody.getCategory()); + Category category = categoryMapper.findCategoryByName(reqBody.getCategory()); if (category == null) { throw new MyException(ResponseEnum.CATEGORY_NOT_EXIST); } - // 构建 需要写入数据库的对象数据 Article article = new Article(); - article.setTitle(reqBody.getTitle()); - article.setOpen(reqBody.getOpen()); - article.setMdContent(reqBody.getMdContent()); - article.setUrl(reqBody.getUrl()); - article.setType(reqBody.getType()); + BeanUtils.copyProperties(reqBody, article); article.setUser(redisUserUtil.get()); - article.setPublishDate(new Date()); //markdown->html->summary String str = StringFromHtmlUtil.getString(MDTool.markdown2Html(article.getMdContent())); @@ -113,14 +103,13 @@ public class ArticleServiceImpl implements ArticleService { //文章存数据库 articleMapper.insert(article); - //将标签写入数据库 for (String tagName : reqBody.getTags()) { if (tagName.replaceAll(" ", "").length() == 0) { //单个标签只含空格 continue; } - Tag tag = (Tag) tagMapper.findTagByName(tagName); + Tag tag = tagMapper.findTagByName(tagName); if (tag == null) { tag = new Tag(); tag.setName(tagName); @@ -129,9 +118,12 @@ public class ArticleServiceImpl implements ArticleService { ArticleTag articleTag = new ArticleTag(article, tag); articleTagMapper.insert(articleTag); } - return fullTransform(article); - } + Article articleFromDb = articleMapper.findArticleById(article.getId()); + ArticleModel articleModel = ModalTrans.articleToModal(articleFromDb); + articleModel.setPreArticle(ModalTrans.articleToModal(articleMapper.getPreArticle(article.getId()))); + return articleModel; + } @Override @Transactional(rollbackFor = Exception.class) @@ -189,7 +181,7 @@ public class ArticleServiceImpl implements ArticleService { article.setUrl(reqBody.getUrl()); } if (reqBody.getCategory() != null && !reqBody.getCategory().replaceAll(" ", "").isEmpty()) { - Category category = (Category) categoryMapper.findCategoryByName(reqBody.getCategory()); + Category category = categoryMapper.findCategoryByName(reqBody.getCategory()); if (category == null) { category = new Category(); category.setName(reqBody.getCategory()); @@ -198,12 +190,8 @@ public class ArticleServiceImpl implements ArticleService { article.setCategory(category); } - if (reqBody.getTags() != null && reqBody.getTags().length != 0) { - - } - //写入数据库的数据 - article.setOpen(reqBody.getOpen() ? article.getOpen() : reqBody.getOpen()); + article.setOpen(reqBody.getOpen() == null ? article.getOpen() : reqBody.getOpen()); String str = StringFromHtmlUtil.getString(MDTool.markdown2Html(article.getMdContent())); article.setSummary(str.length() > 240 ? str.substring(0, 240) + "......" : str); articleMapper.update(article); @@ -213,12 +201,13 @@ public class ArticleServiceImpl implements ArticleService { List updateList = new ArrayList<>(); List deleteList = new ArrayList<>(); + // 获取要更新 的标签 for (String tag : reqBody.getTags()) { boolean contain = allByArticleId.stream().anyMatch(articleTag -> articleTag.getTag().getName().equals(tag)); if (!contain) { ArticleTag articleTag = new ArticleTag(); articleTag.setArticle(article); - Tag tagByName = (Tag) tagMapper.findTagByName(tag); + Tag tagByName = tagMapper.findTagByName(tag); if (tagByName == null) { tagByName = new Tag(tag); tagMapper.insert(tagByName); @@ -227,7 +216,7 @@ public class ArticleServiceImpl implements ArticleService { updateList.add(articleTag); } } - + // 获取要删除的标签 allByArticleId.forEach(articleTag -> { boolean contain = false; for (String tag : reqBody.getTags()) { @@ -251,12 +240,14 @@ public class ArticleServiceImpl implements ArticleService { //更新完成移除 request.getSession().removeAttribute("article4update"); - return fullTransform(article); + ArticleModel articleModel = ModalTrans.articleToModal(articleMapper.findArticleById(article.getId())); + setPreAndNextArticle(articleModel); + return articleModel; } @Override - public ArticleModel retrieveOneByID(long articleID, boolean is4update) { - Article article = articleMapper.findArticleById(articleID); + public ArticleModel retrieveOneById(long articleId, boolean is4update) { + Article article = articleMapper.findArticleById(articleId); if (article == null) { throw new MyException(ResponseEnum.ARTICLE_NOT_EXIST); } @@ -266,178 +257,101 @@ public class ArticleServiceImpl implements ArticleService { throw new MyException(ResponseEnum.ARTICLE_NOT_PUBLIC); } } - article.setReadingNumber(article.getReadingNumber() + 1); + ArticleModel articleModel = ModalTrans.articleToModal(article); + if (is4update) { //因更新而获取文章 不需要增加阅读量 request.getSession().setAttribute("article4update", article); - return fullTransform(article); + return articleModel; } - articleMapper.setReadingNumber(article.getReadingNumber() + 1, articleID); - return fullTransform(article); + setPreAndNextArticle(articleModel); + articleMapper.updateReadingNumber(articleId); + return articleModel; } /** * @param count 数目 * @param page 页面 默认减1 - * @return + * @return PageInfo */ @Override - public PageInfo adminArticles(int count, int page) { + public PageData adminArticles(int count, int page) { PageHelper.startPage(page, count); List
articleList = articleMapper.findAll(); - PageInfo pageInfo = new PageInfo(articleList); - pageInfo.setList(list2list(articleList, LevelEnum.BETWEEN_M_AND_H)); - return pageInfo; + PageData pageData = new PageData(new PageInfo
(articleList)); + List articleModelList = new ArrayList<>(); + articleList.forEach(article -> { + ArticleModel articleModel = ModalTrans.articleToModal(article); + articleModel.setMdContent(null); + articleModelList.add(articleModel); + }); + pageData.setList(articleModelList); + return pageData; } @Override - public PageInfo retrievePageForOpen(int count, int page) { + public PageData retrievePageForOpen(int count, int page) { PageHelper.startPage(page, count); List
articleList = articleMapper.findAllByOpen(true); - PageInfo pageInfo = new PageInfo(articleList); - pageInfo.setList(list2list(articleList, LevelEnum.MIDDLE)); - return pageInfo; + PageData pageData = new PageData<>(new PageInfo
(articleList)); + + List articleModelList = new ArrayList<>(); + + articleList.forEach(article -> { + ArticleModel model = ModalTrans.articleToModal(article); + setPreAndNextArticle(model); + model.setOpen(null); + model.setMdContent(null); + articleModelList.add(model); + }); + + pageData.setList(articleModelList); + return pageData; } @Override - public PageInfo findByCategory(String name, int page, int count) { - Long idByName = categoryMapper.getIdByName(name); - if (idByName == null) { + public PageData findByCategory(String name, int page, int count) { + Category category = categoryMapper.findCategoryByName(name); + if (category == null) { throw new MyException(ResponseEnum.CATEGORY_NOT_EXIST); } PageHelper.startPage(page, count); - PageInfo pageInfo = new PageInfo(articleMapper.getSimpleInfoByCategory(idByName)); - return pageInfo; + List
open = articleMapper.findAllByCategoryIdAndOpen(category.getId()); + + List modelList = new ArrayList<>(); + + open.forEach(article -> { + ArticleModel model = ModalTrans.articleToModal(article); + model.setMdContent(null); + model.setTags(null); + model.setOpen(null); + setPreAndNextArticle(model); + }); + return new PageData(new PageInfo
(open), modelList); } @Override - public PageInfo findByTag(String name, int page, int count) { - Tag tag = (Tag) tagMapper.findTagByName(name); + public PageData findByTag(String name, int page, int count) { + Tag tag = tagMapper.findTagByName(name); if (tag == null) { throw new MyException(ResponseEnum.TAG_NOT_EXIST); } - // TODO : PageHelper.startPage(page, count); - List list = Arrays.asList(null); - List
articleList = articleMapper.getSimpleInfoByTag(list); - PageInfo pageInfo = new PageInfo(articleList); - return pageInfo; + List articleByTag = articleTagMapper.findArticleByTagAndOpen(tag.getId()); + List modelList = new ArrayList<>(); + articleByTag.forEach(articleTag -> { + ArticleModel model = ModalTrans.articleToModal(articleTag.getArticle()); + model.setMdContent(null); + model.setOpen(null); + }); + return new PageData(new PageInfo(articleByTag), modelList); } - /** - * page转换 - * - * @param articleList 数据源 - * @param level 转换级别 - * @return list - */ - private List list2list(List
articleList, LevelEnum level) { - List content = new ArrayList<>(); - for (Article a : articleList) { - ArticleModel model; - switch (level.getLevelCode()) { - case 0: - model = simpleTransform(a); - break; - case 1: - model = suitableTransform(a); - break; - case 2: - model = suitableTransformForAdmin(a); - break; - case 3: - default: - model = fullTransform(a); - } - content.add(model); + private void setPreAndNextArticle(ArticleModel articleModel) { + if (articleModel == null) { + return; } - return content; + articleModel.setPreArticle(ModalTrans.articleToModal(articleMapper.getPreArticle(articleModel.getId()))); + articleModel.setNextArticle(ModalTrans.articleToModal(articleMapper.getNextArticle(articleModel.getId()))); } - - /** - * 简单的模型转换 - * [id,title,summary] - * - * @param a 源数据 - * @return 模型 - */ - private ArticleModel simpleTransform(Article a) { - ArticleModel model = new ArticleModel(); - model.setId(a.getId()); - model.setTitle(a.getTitle()); - model.setSummary(a.getSummary()); - - return model; - } - - /** - * 中等转换 - * [id,title,summary] - * + - * [original,tags,category] - * - * @param a - * @return - */ - private ArticleModel suitableTransform(Article a) { - ArticleModel model = simpleTransform(a); -// model.setAuthor(a.getUser()); -// model.setPublishDateFormat(DateFormatUtil.get(a.getPublishDate())); -// model.setOriginal(a.getType()); -// model.setCategory(categoryMapper.getNameById(a.getCategoryId())); -// String[] split = a.getTagsId().split(","); -// String[] tags = new String[split.length]; -// for (int i = 0; i < split.length; i++) { -// if (split[i] == null || "".equals(split[i])) { -// continue; -// } -// tags[i] = tagMapper.getNameById(Long.parseLong(split[i])); -// } -// model.setTags(tags); - return model; - } - - /** - * 中等转换 for admin页面 - * [id,title] - * + - * [original,UpdateDate,open,readingNumber] - * - * @param a - * @return - */ - private ArticleModel suitableTransformForAdmin(Article a) { - ArticleModel model = simpleTransform(a); -// model.setPublishDateFormat(DateFormatUtil.get(a.getPublishDate())); -// model.setUpdateDateFormat(DateFormatUtil.get(a.getUpdateDate())); -// model.setReadingNumber(a.getReadingNumber()); -// model.setOpen(a.getOpen()); -// model.setOriginal(a.getType()); -// model.setSummary(null); - return model; - } - - /** - * 全转换 - * [id,title,summary,original,tags,category] - * + - * [UpdateDate,MdContent,NextArticleId,NextArticleTitle,preArticleId,preArticleTitle,open,url,readingNumber] - * - * @param a - * @return - */ - private ArticleModel fullTransform(Article a) { - ArticleModel model = suitableTransform(a); -// model.setUpdateDateFormat(DateFormatUtil.get(a.getUpdateDate())); -// model.setMdContent(a.getMdContent()); -// model.setNextArticleId(a.getNextArticleId()); -// model.setNextArticleTitle(a.getNextArticleId() == -1 ? "无" : articleMapper.getTitleById(a.getNextArticleId())); -// model.setPreArticleId(a.getPreArticleId()); -// model.setPreArticleTitle(a.getPreArticleId() == -1 ? "无" : articleMapper.getTitleById(a.getPreArticleId())); -// model.setOpen(a.getOpen()); -// model.setUrl(a.getUrl()); -// model.setReadingNumber(a.getReadingNumber()); - return model; - } - } diff --git a/src/main/java/cn/celess/blog/util/ModalTrans.java b/src/main/java/cn/celess/blog/util/ModalTrans.java new file mode 100644 index 0000000..35ba872 --- /dev/null +++ b/src/main/java/cn/celess/blog/util/ModalTrans.java @@ -0,0 +1,37 @@ +package cn.celess.blog.util; + +import cn.celess.blog.entity.Article; +import cn.celess.blog.entity.User; +import cn.celess.blog.entity.model.ArticleModel; +import cn.celess.blog.entity.model.UserModel; +import org.springframework.beans.BeanUtils; + +/** + * @Author: 小海 + * @Date: 2020-05-24 18:04 + * @Desc: + */ +public class ModalTrans { + + public static ArticleModel articleToModal(Article article) { + if (article == null) { + return null; + } + ArticleModel articleModel = new ArticleModel(); + BeanUtils.copyProperties(article, articleModel); + articleModel.setPublishDateFormat(DateFormatUtil.get(article.getPublishDate())); + articleModel.setUpdateDateFormat(DateFormatUtil.get(article.getUpdateDate())); + articleModel.setOriginal(article.getType()); + articleModel.setCategory(article.getCategory().getName()); + articleModel.setAuthor(userToModal(article.getUser())); + return articleModel; + } + + + public static UserModel userToModal(User user) { + UserModel userModel = new UserModel(); + BeanUtils.copyProperties(user, userModel); + return userModel; + } + +} diff --git a/src/main/resources/mapper/ArticleTagMapper.xml b/src/main/resources/mapper/ArticleTagMapper.xml index b8458e1..c1062b3 100644 --- a/src/main/resources/mapper/ArticleTagMapper.xml +++ b/src/main/resources/mapper/ArticleTagMapper.xml @@ -43,8 +43,8 @@ delete from article_tag where at_id in - - (#{articleTag.id}) + + #{item.id} @@ -73,4 +73,28 @@ and tag_category.t_id = article_tag.t_id + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/articleMapper.xml b/src/main/resources/mapper/articleMapper.xml index 19fc2c9..c15deb5 100644 --- a/src/main/resources/mapper/articleMapper.xml +++ b/src/main/resources/mapper/articleMapper.xml @@ -141,6 +141,15 @@ order by articleId desc + + + + + \ No newline at end of file diff --git a/src/test/java/cn/celess/blog/controller/ArticleControllerTest.java b/src/test/java/cn/celess/blog/controller/ArticleControllerTest.java index 4b71094..4d16a34 100644 --- a/src/test/java/cn/celess/blog/controller/ArticleControllerTest.java +++ b/src/test/java/cn/celess/blog/controller/ArticleControllerTest.java @@ -3,10 +3,11 @@ package cn.celess.blog.controller; import cn.celess.blog.BaseTest; import cn.celess.blog.entity.Article; import cn.celess.blog.entity.Response; +import cn.celess.blog.entity.Tag; import cn.celess.blog.entity.model.ArticleModel; +import cn.celess.blog.entity.model.PageData; import cn.celess.blog.entity.request.ArticleReq; import cn.celess.blog.mapper.ArticleMapper; -import com.github.pagehelper.PageInfo; import net.sf.json.JSONObject; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -31,7 +32,8 @@ public class ArticleControllerTest extends BaseTest { articleReq.setTitle("test-" + UUID.randomUUID().toString()); articleReq.setMdContent("# test title"); articleReq.setCategory("随笔"); - articleReq.setTags("test,SpringMvc"); + String[] tagList = {"tag", "category"}; + articleReq.setTags(tagList); articleReq.setOpen(true); articleReq.setType(true); articleReq.setUrl("http://xxxx.com"); @@ -80,13 +82,11 @@ public class ArticleControllerTest extends BaseTest { assertNotNull(articleModel.getCategory()); assertNotNull(articleModel.getPublishDateFormat()); assertNotNull(articleModel.getMdContent()); - assertNotNull(articleModel.getNextArticleId()); - assertNotNull(articleModel.getNextArticleTitle()); - assertNotNull(articleModel.getPreArticleId()); - assertNotNull(articleModel.getPreArticleTitle()); + assertNotNull(articleModel.getPreArticle()); + assertNull(articleModel.getNextArticle()); assertNotNull(articleModel.getOpen()); assertNotNull(articleModel.getReadingNumber()); - assertNotNull(articleModel.getAuthorName()); + assertNotNull(articleModel.getAuthor()); assertNotNull(articleModel.getUrl()); }); } catch (Exception e) { @@ -96,11 +96,11 @@ public class ArticleControllerTest extends BaseTest { @Test public void delete() { - long articleId = articleMapper.getLastestArticleId(); + Article article = articleMapper.getLastestArticle(); try { // 未登录删除文章 - mockMvc.perform(MockMvcRequestBuilders.delete("/admin/article/del?articleID=" + articleId) + mockMvc.perform(MockMvcRequestBuilders.delete("/admin/article/del?articleID=" + article.getId()) ).andDo(result -> { assertEquals(HAVE_NOT_LOG_IN.getCode(), JSONObject.fromObject(result.getResponse().getContentAsString()).getInt(Code) @@ -108,14 +108,14 @@ public class ArticleControllerTest extends BaseTest { }); // user 权限删除文章 String token = userLogin(); - mockMvc.perform(MockMvcRequestBuilders.delete("/admin/article/del?articleID=" + articleId) + mockMvc.perform(MockMvcRequestBuilders.delete("/admin/article/del?articleID=" + article.getId()) .header("Authorization", token)) .andDo(result -> assertEquals(PERMISSION_ERROR.getCode(), JSONObject.fromObject(result.getResponse().getContentAsString()).getInt(Code)) ); // admin 权限删除文章 token = adminLogin(); - mockMvc.perform(MockMvcRequestBuilders.delete("/admin/article/del?articleID=" + articleId) + mockMvc.perform(MockMvcRequestBuilders.delete("/admin/article/del?articleID=" + article.getId()) .header("Authorization", token)) .andDo(result -> { JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString()); @@ -140,8 +140,8 @@ public class ArticleControllerTest extends BaseTest { articleReq.setOpen(!article.getOpen()); String tag1 = randomStr(4); String tag2 = randomStr(4); - String tag = "test," + tag1 + "," + tag2; - articleReq.setTags(tag); + String[] tagList = {"test", tag1, tag2}; + articleReq.setTags(tagList); articleReq.setTitle("test-" + article.getTitle()); try { // Admin 权限 @@ -160,15 +160,11 @@ public class ArticleControllerTest extends BaseTest { assertEquals(articleReq.getTitle(), a.getTitle()); assertEquals(articleReq.getType(), a.getOriginal()); // Tag - List asList = Arrays.asList(a.getTags()); - assertTrue(asList.contains("test")); - assertTrue(asList.contains(tag1)); - assertTrue(asList.contains(tag2)); + List asList = a.getTags(); + assertEquals(3, asList.size()); assertEquals(articleReq.getOpen(), a.getOpen()); assertEquals(articleReq.getId(), a.getId()); }); - - } catch (Exception e) { e.printStackTrace(); } @@ -207,17 +203,13 @@ public class ArticleControllerTest extends BaseTest { assertNotNull(a.getMdContent()); assertNotNull(a.getUrl()); assertNotNull(a.getUpdateDateFormat()); - assertNotNull(a.getPreArticleId()); - assertNotNull(a.getPreArticleId()); - assertNotNull(a.getNextArticleId()); - assertNotNull(a.getNextArticleTitle()); + assertTrue(a.getPreArticle() != null || a.getNextArticle() != null); assertNotNull(a.getReadingNumber()); - // assertNotNull(a.getOpen()); assertNotNull(a.getOriginal()); assertNotNull(a.getPublishDateFormat()); assertNotNull(a.getCategory()); assertNotNull(a.getTags()); - assertNotNull(a.getAuthorName()); + assertNotNull(a.getAuthor()); }); } catch (Exception e) { e.printStackTrace(); @@ -242,14 +234,12 @@ public class ArticleControllerTest extends BaseTest { assertNotNull(response.getResult()); // 判断pageInfo是否包装完全 JSONObject resultJson = JSONObject.fromObject(response.getResult()); - PageInfo pageInfo = (PageInfo) JSONObject.toBean(resultJson, PageInfo.class); - assertNotEquals(0, pageInfo.getTotal()); - assertNotEquals(0, pageInfo.getStartRow()); - assertNotEquals(0, pageInfo.getEndRow()); - assertEquals(1, pageInfo.getPageNum()); - assertEquals(5, pageInfo.getPageSize()); + PageData pageData = (PageData) JSONObject.toBean(resultJson, PageData.class); + assertNotEquals(0, pageData.getTotal()); + assertEquals(1, pageData.getPageNum()); + assertEquals(5, pageData.getPageSize()); // 内容完整 - for (Object arc : pageInfo.getList()) { + for (Object arc : pageData.getList()) { ArticleModel a = (ArticleModel) JSONObject.toBean(JSONObject.fromObject(arc), ArticleModel.class); assertNotNull(a.getTitle()); assertNotNull(a.getId()); @@ -258,7 +248,9 @@ public class ArticleControllerTest extends BaseTest { assertNotNull(a.getPublishDateFormat()); assertNotNull(a.getCategory()); assertNotNull(a.getTags()); - assertNotNull(a.getAuthorName()); + assertNotNull(a.getAuthor()); + assertNull(a.getOpen()); + assertNull(a.getMdContent()); } }); } catch (Exception e) { @@ -299,14 +291,12 @@ public class ArticleControllerTest extends BaseTest { assertEquals(SUCCESS.getCode(), adminLogin.getInt(Code)); assertNotNull(adminLogin.getString(Result)); // 判断pageInfo是否包装完全 - PageInfo pageInfo = (PageInfo) JSONObject.toBean(adminLogin.getJSONObject(Result), PageInfo.class); - assertNotEquals(0, pageInfo.getTotal()); - assertNotEquals(0, pageInfo.getStartRow()); - assertNotEquals(0, pageInfo.getEndRow()); - assertEquals(1, pageInfo.getPageNum()); - assertEquals(10, pageInfo.getPageSize()); + PageData pageData = (PageData) JSONObject.toBean(adminLogin.getJSONObject(Result), PageData.class); + assertNotEquals(0, pageData.getTotal()); + assertEquals(1, pageData.getPageNum()); + assertEquals(10, pageData.getPageSize()); // 内容完整 - for (Object arc : pageInfo.getList()) { + for (Object arc : pageData.getList()) { ArticleModel a = (ArticleModel) JSONObject.toBean(JSONObject.fromObject(arc), ArticleModel.class); assertNotNull(a.getTitle()); assertNotNull(a.getId()); @@ -314,6 +304,9 @@ public class ArticleControllerTest extends BaseTest { assertNotNull(a.getPublishDateFormat()); assertNotNull(a.getOpen()); assertNotNull(a.getReadingNumber()); + assertNotNull(a.getLikeCount()); + assertNotNull(a.getDislikeCount()); + assertNull(a.getMdContent()); } }); } catch (Exception e) { @@ -338,13 +331,11 @@ public class ArticleControllerTest extends BaseTest { .andDo(result -> { JSONObject jsonObject = JSONObject.fromObject(result.getResponse().getContentAsString()); assertEquals(SUCCESS.getCode(), jsonObject.getInt(Code)); - PageInfo pageInfo = (PageInfo) JSONObject.toBean(jsonObject.getJSONObject(Result), PageInfo.class); - assertNotEquals(0, pageInfo.getTotal()); - assertNotEquals(0, pageInfo.getStartRow()); - assertNotEquals(0, pageInfo.getEndRow()); - assertEquals(1, pageInfo.getPageNum()); - assertEquals(10, pageInfo.getPageSize()); - for (Object arc : pageInfo.getList()) { + PageData pageData = (PageData) JSONObject.toBean(jsonObject.getJSONObject(Result), PageData.class); + assertNotEquals(0, pageData.getTotal()); + assertEquals(1, pageData.getPageNum()); + assertEquals(10, pageData.getPageSize()); + for (Object arc : pageData.getList()) { JSONObject jsonObject1 = JSONObject.fromObject(arc); assertNotEquals(0, jsonObject1.getInt("id")); assertNotNull(jsonObject1.getString("title")); @@ -373,14 +364,12 @@ public class ArticleControllerTest extends BaseTest { .andDo(result -> { JSONObject jsonObject = JSONObject.fromObject(result.getResponse().getContentAsString()); assertEquals(SUCCESS.getCode(), jsonObject.getInt(Code)); - PageInfo pageInfo = (PageInfo) JSONObject.toBean(jsonObject.getJSONObject(Result), PageInfo.class); - assertNotEquals(0, pageInfo.getTotal()); - assertNotEquals(0, pageInfo.getStartRow()); - assertNotEquals(0, pageInfo.getEndRow()); - assertEquals(1, pageInfo.getPageNum()); - assertEquals(10, pageInfo.getPageSize()); + PageData pageData = (PageData) JSONObject.toBean(jsonObject.getJSONObject(Result), PageData.class); + assertNotEquals(0, pageData.getTotal()); + assertEquals(1, pageData.getPageNum()); + assertEquals(10, pageData.getPageSize()); - for (Object arc : pageInfo.getList()) { + for (Object arc : pageData.getList()) { JSONObject jsonObject1 = JSONObject.fromObject(arc); assertNotEquals(0, jsonObject1.getInt("id")); assertNotNull(jsonObject1.getString("title")); diff --git a/src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java b/src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java index 5a7921a..1b7d785 100644 --- a/src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java +++ b/src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java @@ -162,6 +162,13 @@ public class ArticleMapperTest extends BaseTest { assertNotEquals(0, allByCategoryId.size()); } + @Test + public void findAllByCategoryIdAndOpen() { + List
allByCategoryId = articleMapper.findAllByCategoryId(1); + assertNotEquals(0, allByCategoryId.size()); + allByCategoryId.forEach(article -> assertTrue(article.getOpen())); + } + @Test public void findAll() { List
allByCategoryId = articleMapper.findAll(); @@ -173,6 +180,21 @@ public class ArticleMapperTest extends BaseTest { assertNotEquals(0, articleMapper.count()); } + @Test + public void getPreArticle() { + ArticleTag articleTag = generateArticle(); + Article preArticle = articleMapper.getPreArticle(articleTag.getArticle().getId()); + assertNotNull(preArticle); + assertTrue(preArticle.getId() < articleTag.getArticle().getId()); + } + + @Test + public void getNextArticle() { + Article getNextArticle = articleMapper.getNextArticle(3L); + assertNotNull(getNextArticle); + assertTrue(getNextArticle.getId() > 3L); + } + private ArticleTag generateArticle() { String randomText = UUID.randomUUID().toString(); @@ -199,5 +221,4 @@ public class ArticleMapperTest extends BaseTest { return articleTag; } - } \ No newline at end of file diff --git a/src/test/java/cn/celess/blog/mapper/ArticleTagMapperTest.java b/src/test/java/cn/celess/blog/mapper/ArticleTagMapperTest.java index 115d90c..fb8715d 100644 --- a/src/test/java/cn/celess/blog/mapper/ArticleTagMapperTest.java +++ b/src/test/java/cn/celess/blog/mapper/ArticleTagMapperTest.java @@ -90,11 +90,27 @@ public class ArticleTagMapperTest extends BaseTest { articleTagMapper.insert(articleTag); List allByArticleId = articleTagMapper.findAllByArticleId(-1L); - assertEquals(6, allByArticleId.size()); + assertTrue(allByArticleId.size() >= 6); int lines = articleTagMapper.deleteMultiById(allByArticleId); - assertEquals(6, lines); + assertTrue(lines >= 6); } + @Test + public void findArticleByTag() { + ArticleTag articleTag = generateArticle(); + List articleByTag = articleTagMapper.findArticleByTag(21L); + assertNotEquals(0, articleByTag.size()); + articleByTag.forEach(articleTag1 -> assertEquals(articleTag.getTag().getName(), articleTag1.getTag().getName())); + } + + @Test + public void findArticleByTagAndOpen() { + ArticleTag articleTag = generateArticle(); + List articleByTag = articleTagMapper.findArticleByTag(21L); + assertNotEquals(0, articleByTag.size()); + articleByTag.forEach(articleTag1 -> assertEquals(articleTag.getTag().getName(), articleTag1.getTag().getName())); + articleByTag.forEach(articleTag1 -> assertTrue(articleTag1.getArticle().getOpen())); + } private ArticleTag generateArticle() { String randomText = UUID.randomUUID().toString(); @@ -122,5 +138,4 @@ public class ArticleTagMapperTest extends BaseTest { return articleTag; } - } \ No newline at end of file From ae7d063fdd35185a8f49e4a454996eea4724dfe0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Mon, 25 May 2020 22:05:46 +0800 Subject: [PATCH 13/33] =?UTF-8?q?Service=E5=B1=82=E4=BF=AE=E6=94=B9=20=20?= =?UTF-8?q?=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cn/celess/blog/service/ArticleService.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/cn/celess/blog/service/ArticleService.java b/src/main/java/cn/celess/blog/service/ArticleService.java index 36f706e..fb15add 100644 --- a/src/main/java/cn/celess/blog/service/ArticleService.java +++ b/src/main/java/cn/celess/blog/service/ArticleService.java @@ -1,8 +1,8 @@ package cn.celess.blog.service; import cn.celess.blog.entity.model.ArticleModel; +import cn.celess.blog.entity.model.PageData; import cn.celess.blog.entity.request.ArticleReq; -import com.github.pagehelper.PageInfo; import org.springframework.stereotype.Service; @@ -39,11 +39,11 @@ public interface ArticleService { /** * 获取一篇文章的数据 * - * @param articleID 文章id + * @param articleId 文章id * @param is4update 是否是因文章更新而请求数据 * @return 文章数据 */ - ArticleModel retrieveOneByID(long articleID, boolean is4update); + ArticleModel retrieveOneById(long articleId, boolean is4update); /** * 管理员 获取分页数据 @@ -52,7 +52,7 @@ public interface ArticleService { * @param page 数据页 * @return 分页数据 */ - PageInfo adminArticles(int count, int page); + PageData adminArticles(int count, int page); /** * 获取文章状态为开放的文章 @@ -61,7 +61,7 @@ public interface ArticleService { * @param page 数据页 * @return 分页数据 */ - PageInfo retrievePageForOpen(int count, int page); + PageData retrievePageForOpen(int count, int page); /** * 根据分类名获取文章数据 @@ -71,7 +71,7 @@ public interface ArticleService { * @param page 数据页 * @return 分页数据 */ - PageInfo findByCategory(String name, int page, int count); + PageData findByCategory(String name, int page, int count); /** * 根据标签名获取文章数据 @@ -81,5 +81,5 @@ public interface ArticleService { * @param page 数据页 * @return 分页数据 */ - PageInfo findByTag(String name, int page, int count); + PageData findByTag(String name, int page, int count); } From c4ed6602e777bb99f5492a1bdda3a416df8f263e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Mon, 25 May 2020 22:06:13 +0800 Subject: [PATCH 14/33] rename method --- .../serviceimpl/ArticleServiceImpl.java | 20 +++++++++---------- .../java/cn/celess/blog/util/ModalTrans.java | 13 +++++++++--- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/ArticleServiceImpl.java b/src/main/java/cn/celess/blog/service/serviceimpl/ArticleServiceImpl.java index 7a7eeda..f3e575d 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/ArticleServiceImpl.java +++ b/src/main/java/cn/celess/blog/service/serviceimpl/ArticleServiceImpl.java @@ -120,8 +120,8 @@ public class ArticleServiceImpl implements ArticleService { } Article articleFromDb = articleMapper.findArticleById(article.getId()); - ArticleModel articleModel = ModalTrans.articleToModal(articleFromDb); - articleModel.setPreArticle(ModalTrans.articleToModal(articleMapper.getPreArticle(article.getId()))); + ArticleModel articleModel = ModalTrans.article(articleFromDb); + articleModel.setPreArticle(ModalTrans.article(articleMapper.getPreArticle(article.getId()))); return articleModel; } @@ -240,7 +240,7 @@ public class ArticleServiceImpl implements ArticleService { //更新完成移除 request.getSession().removeAttribute("article4update"); - ArticleModel articleModel = ModalTrans.articleToModal(articleMapper.findArticleById(article.getId())); + ArticleModel articleModel = ModalTrans.article(articleMapper.findArticleById(article.getId())); setPreAndNextArticle(articleModel); return articleModel; } @@ -257,7 +257,7 @@ public class ArticleServiceImpl implements ArticleService { throw new MyException(ResponseEnum.ARTICLE_NOT_PUBLIC); } } - ArticleModel articleModel = ModalTrans.articleToModal(article); + ArticleModel articleModel = ModalTrans.article(article); if (is4update) { //因更新而获取文章 不需要增加阅读量 @@ -281,7 +281,7 @@ public class ArticleServiceImpl implements ArticleService { PageData pageData = new PageData(new PageInfo
(articleList)); List articleModelList = new ArrayList<>(); articleList.forEach(article -> { - ArticleModel articleModel = ModalTrans.articleToModal(article); + ArticleModel articleModel = ModalTrans.article(article); articleModel.setMdContent(null); articleModelList.add(articleModel); }); @@ -298,7 +298,7 @@ public class ArticleServiceImpl implements ArticleService { List articleModelList = new ArrayList<>(); articleList.forEach(article -> { - ArticleModel model = ModalTrans.articleToModal(article); + ArticleModel model = ModalTrans.article(article); setPreAndNextArticle(model); model.setOpen(null); model.setMdContent(null); @@ -321,7 +321,7 @@ public class ArticleServiceImpl implements ArticleService { List modelList = new ArrayList<>(); open.forEach(article -> { - ArticleModel model = ModalTrans.articleToModal(article); + ArticleModel model = ModalTrans.article(article); model.setMdContent(null); model.setTags(null); model.setOpen(null); @@ -340,7 +340,7 @@ public class ArticleServiceImpl implements ArticleService { List articleByTag = articleTagMapper.findArticleByTagAndOpen(tag.getId()); List modelList = new ArrayList<>(); articleByTag.forEach(articleTag -> { - ArticleModel model = ModalTrans.articleToModal(articleTag.getArticle()); + ArticleModel model = ModalTrans.article(articleTag.getArticle()); model.setMdContent(null); model.setOpen(null); }); @@ -351,7 +351,7 @@ public class ArticleServiceImpl implements ArticleService { if (articleModel == null) { return; } - articleModel.setPreArticle(ModalTrans.articleToModal(articleMapper.getPreArticle(articleModel.getId()))); - articleModel.setNextArticle(ModalTrans.articleToModal(articleMapper.getNextArticle(articleModel.getId()))); + articleModel.setPreArticle(ModalTrans.article(articleMapper.getPreArticle(articleModel.getId()))); + articleModel.setNextArticle(ModalTrans.article(articleMapper.getNextArticle(articleModel.getId()))); } } diff --git a/src/main/java/cn/celess/blog/util/ModalTrans.java b/src/main/java/cn/celess/blog/util/ModalTrans.java index 35ba872..e518da6 100644 --- a/src/main/java/cn/celess/blog/util/ModalTrans.java +++ b/src/main/java/cn/celess/blog/util/ModalTrans.java @@ -1,8 +1,10 @@ package cn.celess.blog.util; import cn.celess.blog.entity.Article; +import cn.celess.blog.entity.Category; import cn.celess.blog.entity.User; import cn.celess.blog.entity.model.ArticleModel; +import cn.celess.blog.entity.model.CategoryModel; import cn.celess.blog.entity.model.UserModel; import org.springframework.beans.BeanUtils; @@ -13,7 +15,7 @@ import org.springframework.beans.BeanUtils; */ public class ModalTrans { - public static ArticleModel articleToModal(Article article) { + public static ArticleModel article(Article article) { if (article == null) { return null; } @@ -23,15 +25,20 @@ public class ModalTrans { articleModel.setUpdateDateFormat(DateFormatUtil.get(article.getUpdateDate())); articleModel.setOriginal(article.getType()); articleModel.setCategory(article.getCategory().getName()); - articleModel.setAuthor(userToModal(article.getUser())); + articleModel.setAuthor(user(article.getUser())); return articleModel; } - public static UserModel userToModal(User user) { + public static UserModel user(User user) { UserModel userModel = new UserModel(); BeanUtils.copyProperties(user, userModel); return userModel; } + public static CategoryModel category(Category category) { + CategoryModel model = new CategoryModel(); + BeanUtils.copyProperties(category, model); + return model; + } } From d19e5b62866bd8862e4d1e363b4d331d51589587 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Mon, 25 May 2020 22:18:50 +0800 Subject: [PATCH 15/33] =?UTF-8?q?Service=E5=B1=82=E4=BF=AE=E6=94=B9=20=20?= =?UTF-8?q?=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../blog/controller/CategoryController.java | 5 +- .../blog/entity/model/CategoryModel.java | 23 +--------- .../celess/blog/service/CategoryService.java | 11 +---- .../serviceimpl/CategoryServiceImpl.java | 46 +++++-------------- src/main/resources/mapper/CategoryMapper.xml | 14 +++--- .../controller/CategoryControllerTest.java | 6 +-- 6 files changed, 29 insertions(+), 76 deletions(-) diff --git a/src/main/java/cn/celess/blog/controller/CategoryController.java b/src/main/java/cn/celess/blog/controller/CategoryController.java index c9a7fab..59617ff 100644 --- a/src/main/java/cn/celess/blog/controller/CategoryController.java +++ b/src/main/java/cn/celess/blog/controller/CategoryController.java @@ -57,7 +57,8 @@ public class CategoryController { * @return Response */ @GetMapping("/categories") - public Response getPage() { - return ResponseUtil.success(categoryService.retrievePage()); + public Response getPage(@RequestParam(name = "page", defaultValue = "1") int page, + @RequestParam(name = "count", defaultValue = "1000") int count) { + return ResponseUtil.success(categoryService.retrievePage(page, count)); } } diff --git a/src/main/java/cn/celess/blog/entity/model/CategoryModel.java b/src/main/java/cn/celess/blog/entity/model/CategoryModel.java index f601030..e99d57c 100644 --- a/src/main/java/cn/celess/blog/entity/model/CategoryModel.java +++ b/src/main/java/cn/celess/blog/entity/model/CategoryModel.java @@ -1,12 +1,10 @@ package cn.celess.blog.entity.model; -import cn.celess.blog.entity.Category; +import cn.celess.blog.entity.Article; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -import java.util.ArrayList; -import java.util.Arrays; import java.util.List; /** @@ -22,22 +20,5 @@ public class CategoryModel { private String name; - private List articles; - - - public CategoryModel(Category category) { - this.id = category.getId(); - this.name = category.getName(); - if (category.getArticles() == null || category.getArticles().length() == 0) { - articles = null; - } else { - articles = new ArrayList<>(); - for (String s : category.getArticles().split(",")) { - if ("".equals(s)) { - return; - } - articles.add(Integer.parseInt(s)); - } - } - } + private List
articles; } diff --git a/src/main/java/cn/celess/blog/service/CategoryService.java b/src/main/java/cn/celess/blog/service/CategoryService.java index d5e5470..b40da6d 100644 --- a/src/main/java/cn/celess/blog/service/CategoryService.java +++ b/src/main/java/cn/celess/blog/service/CategoryService.java @@ -2,6 +2,7 @@ package cn.celess.blog.service; import cn.celess.blog.entity.Category; import cn.celess.blog.entity.model.CategoryModel; +import cn.celess.blog.entity.model.PageData; import org.springframework.stereotype.Service; import java.util.List; @@ -20,14 +21,6 @@ public interface CategoryService { */ CategoryModel create(String name); - /** - * 增加一个分类 - * - * @param category 分类对象 - * @return 所增加的分类数据 - */ - CategoryModel create(Category category); - /** * 通过id删除分类 * @@ -50,6 +43,6 @@ public interface CategoryService { * * @return 全部的分类数据 */ - List retrievePage(); + PageData retrievePage(int page, int count); } diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/CategoryServiceImpl.java b/src/main/java/cn/celess/blog/service/serviceimpl/CategoryServiceImpl.java index e76062a..a2236b2 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/CategoryServiceImpl.java +++ b/src/main/java/cn/celess/blog/service/serviceimpl/CategoryServiceImpl.java @@ -1,13 +1,16 @@ package cn.celess.blog.service.serviceimpl; import cn.celess.blog.enmu.ResponseEnum; -import cn.celess.blog.entity.Article; import cn.celess.blog.entity.Category; import cn.celess.blog.entity.model.CategoryModel; +import cn.celess.blog.entity.model.PageData; import cn.celess.blog.exception.MyException; import cn.celess.blog.mapper.ArticleMapper; import cn.celess.blog.mapper.CategoryMapper; import cn.celess.blog.service.CategoryService; +import cn.celess.blog.util.ModalTrans; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -35,46 +38,19 @@ public class CategoryServiceImpl implements CategoryService { } Category category = new Category(); category.setName(name); - category.setArticles(""); categoryMapper.insert(category); - return new CategoryModel(category); - } - - @Override - public CategoryModel create(Category category) { - if (category == null) { - throw new MyException(ResponseEnum.PARAMETERS_ERROR); - } - categoryMapper.insert(category); - return new CategoryModel(category); + return ModalTrans.category(category); } @Override public boolean delete(long id) { Category category = categoryMapper.findCategoryById(id); - if (category == null) { throw new MyException(ResponseEnum.CATEGORY_NOT_EXIST); } - String[] articleArray = category.getArticles().split(","); - for (int i = 0; i < articleArray.length; i++) { - if (articleArray[i] == null || "".equals(articleArray[i])) { - continue; - } - long articleId = Long.parseLong(articleArray[i]); - Article article = articleMapper.findArticleById(articleId); - if (article == null) { - continue; - } - article.setCategoryId(-1L); - //一个 文章只对应一个分类,分类不存在则文章默认不可见 - article.setOpen(false); - articleMapper.update(article); - } return categoryMapper.delete(id) == 1; } - @Override public CategoryModel update(Long id, String name) { if (id == null) { @@ -83,13 +59,15 @@ public class CategoryServiceImpl implements CategoryService { Category category = categoryMapper.findCategoryById(id); category.setName(name); categoryMapper.update(category); - return new CategoryModel(category); + return ModalTrans.category(category); } @Override - public List retrievePage() { - List list = new ArrayList<>(); - categoryMapper.findAll().forEach(e -> list.add(new CategoryModel(e))); - return list; + public PageData retrievePage(int page, int count) { + PageHelper.startPage(page, count); + List all = categoryMapper.findAll(); + List modelList = new ArrayList<>(); + all.forEach(e -> modelList.add(ModalTrans.category(e))); + return new PageData(new PageInfo(all), modelList); } } diff --git a/src/main/resources/mapper/CategoryMapper.xml b/src/main/resources/mapper/CategoryMapper.xml index 21363ea..b22ba44 100644 --- a/src/main/resources/mapper/CategoryMapper.xml +++ b/src/main/resources/mapper/CategoryMapper.xml @@ -17,47 +17,47 @@ update tag_category set t_name=#{name} where t_id = #{id} - and is_category = true; + and is_category = true update tag_category set is_delete= true where t_id = #{id} - and is_category = true; + and is_category = true select * from tag_category - where is_category = false; + where is_category = false select count(*) from tag_category - where is_category = true; + where is_category = true + and is_delete = false; \ No newline at end of file diff --git a/src/main/resources/mapper/CommentMapper.xml b/src/main/resources/mapper/CommentMapper.xml index 89037f1..2bc43bb 100644 --- a/src/main/resources/mapper/CommentMapper.xml +++ b/src/main/resources/mapper/CommentMapper.xml @@ -108,5 +108,9 @@ limit 1 + diff --git a/src/main/resources/mapper/UserMapper.xml b/src/main/resources/mapper/UserMapper.xml index f1f720a..151740a 100644 --- a/src/main/resources/mapper/UserMapper.xml +++ b/src/main/resources/mapper/UserMapper.xml @@ -120,6 +120,7 @@ select count(*) - from article; + from article + where is_delete = false; select count(*) from tag_category - where is_category = false;; + where is_category = false + and is_delete = false; \ No newline at end of file From 9582725b3a371b31368a72cb6289be5f15d3398b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Tue, 26 May 2020 00:16:09 +0800 Subject: [PATCH 22/33] =?UTF-8?q?=E4=BF=AE=E6=94=B9=20=20=E5=8D=95?= =?UTF-8?q?=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/cn/celess/blog/mapper/CommentMapper.java | 2 ++ src/main/java/cn/celess/blog/service/CountService.java | 7 ------- .../celess/blog/service/serviceimpl/CountServiceImpl.java | 7 +------ src/main/resources/mapper/CommentMapper.xml | 2 +- 4 files changed, 4 insertions(+), 14 deletions(-) diff --git a/src/main/java/cn/celess/blog/mapper/CommentMapper.java b/src/main/java/cn/celess/blog/mapper/CommentMapper.java index 141bc5f..c79cd84 100644 --- a/src/main/java/cn/celess/blog/mapper/CommentMapper.java +++ b/src/main/java/cn/celess/blog/mapper/CommentMapper.java @@ -37,4 +37,6 @@ public interface CommentMapper { List findAllByPagePathAndPid(String pagePath, long pid); long countByPagePath(String pagePath); + + long count(); } diff --git a/src/main/java/cn/celess/blog/service/CountService.java b/src/main/java/cn/celess/blog/service/CountService.java index b553031..7267ece 100644 --- a/src/main/java/cn/celess/blog/service/CountService.java +++ b/src/main/java/cn/celess/blog/service/CountService.java @@ -36,13 +36,6 @@ public interface CountService { */ long getTagsCount(); - /** - * 获取留言数量 - * - * @return 留言数量 - */ - long getLeaveMessageCount(); - /** * 获取用户量 * diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/CountServiceImpl.java b/src/main/java/cn/celess/blog/service/serviceimpl/CountServiceImpl.java index 3165768..fecd29b 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/CountServiceImpl.java +++ b/src/main/java/cn/celess/blog/service/serviceimpl/CountServiceImpl.java @@ -29,7 +29,7 @@ public class CountServiceImpl implements CountService { @Override public long getCommentCount() { - return commentMapper.countByType(true); + return commentMapper.count(); } @Override @@ -47,11 +47,6 @@ public class CountServiceImpl implements CountService { return tagMapper.count(); } - @Override - public long getLeaveMessageCount() { - return commentMapper.countByType(false); - } - @Override public long getUserCount() { return userMapper.count(); diff --git a/src/main/resources/mapper/CommentMapper.xml b/src/main/resources/mapper/CommentMapper.xml index 2bc43bb..6c7026e 100644 --- a/src/main/resources/mapper/CommentMapper.xml +++ b/src/main/resources/mapper/CommentMapper.xml @@ -108,7 +108,7 @@ limit 1 - select count(*) from article where is_delete = false; From fde9b8511c1a0c8b20b793a8978f44c699157082 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Tue, 26 May 2020 00:27:50 +0800 Subject: [PATCH 23/33] =?UTF-8?q?Service=E5=B1=82=E4=BF=AE=E6=94=B9=20=20?= =?UTF-8?q?=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/cn/celess/blog/controller/Other.java | 1 - .../cn/celess/blog/service/UserService.java | 35 ++-------- .../service/serviceimpl/UserServiceImpl.java | 70 ++++--------------- .../java/cn/celess/blog/util/ModalTrans.java | 5 ++ .../blog/controller/UserControllerTest.java | 37 +++++----- 5 files changed, 43 insertions(+), 105 deletions(-) diff --git a/src/main/java/cn/celess/blog/controller/Other.java b/src/main/java/cn/celess/blog/controller/Other.java index e4473ed..8f18ea5 100644 --- a/src/main/java/cn/celess/blog/controller/Other.java +++ b/src/main/java/cn/celess/blog/controller/Other.java @@ -55,7 +55,6 @@ public class Other { Map countMap = new HashMap<>(); countMap.put("articleCount", countService.getArticleCount()); countMap.put("commentCount", countService.getCommentCount()); - countMap.put("leaveMsgCount", countService.getLeaveMessageCount()); countMap.put("categoryCount", countService.getCategoriesCount()); countMap.put("tagCount", countService.getTagsCount()); countMap.put("visitorCount", countService.getVisitorCount()); diff --git a/src/main/java/cn/celess/blog/service/UserService.java b/src/main/java/cn/celess/blog/service/UserService.java index 36ca86b..492ffdf 100644 --- a/src/main/java/cn/celess/blog/service/UserService.java +++ b/src/main/java/cn/celess/blog/service/UserService.java @@ -1,6 +1,7 @@ package cn.celess.blog.service; import cn.celess.blog.entity.User; +import cn.celess.blog.entity.model.PageData; import cn.celess.blog.entity.model.UserModel; import cn.celess.blog.entity.request.LoginReq; import cn.celess.blog.entity.request.UserReq; @@ -42,14 +43,6 @@ public interface UserService { */ Object logout(); - /** - * 获取用户头像的链接 - * - * @param id 用户id - * @return 头像链接 - */ - String getAvatarImg(long id); - /** * 更新用户数据 * @@ -83,14 +76,6 @@ public interface UserService { */ String getUserRoleByEmail(String email); - /** - * 通过邮箱获取用户的信息 - * - * @param email 用户邮箱 - * @return 用户信息 - */ - User getUserInfoByEmail(String email); - /** * 获取邮箱是否注册过 * @@ -99,14 +84,6 @@ public interface UserService { */ boolean isExistOfEmail(String email); - /** - * 获取用户的name 优先返回displayName 否则返回email - * - * @param id 用户id - * @return name - */ - String getNameById(long id); - /** * 发送重置密码邮件 * @@ -157,7 +134,7 @@ public interface UserService { * @param page 数据页 * @return 分页数据 */ - PageInfo getUserList(Integer page, Integer count); + PageData getUserList(Integer page, Integer count); /** * 更改用户信息 @@ -177,10 +154,10 @@ public interface UserService { /** * 设置密码 - * @param pwd - * @param newPwd - * @param confirmPwd - * @return + * @param pwd pwd + * @param newPwd newPwd + * @param confirmPwd confirmPwd + * @return UserModel */ UserModel setPwd(String pwd, String newPwd, String confirmPwd); } diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/UserServiceImpl.java b/src/main/java/cn/celess/blog/service/serviceimpl/UserServiceImpl.java index ecbbe73..02cabb6 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/UserServiceImpl.java +++ b/src/main/java/cn/celess/blog/service/serviceimpl/UserServiceImpl.java @@ -1,7 +1,9 @@ package cn.celess.blog.service.serviceimpl; import cn.celess.blog.enmu.ResponseEnum; +import cn.celess.blog.enmu.RoleEnum; import cn.celess.blog.entity.User; +import cn.celess.blog.entity.model.PageData; import cn.celess.blog.entity.model.QiniuResponse; import cn.celess.blog.entity.model.UserModel; import cn.celess.blog.entity.request.LoginReq; @@ -26,7 +28,6 @@ import javax.servlet.http.HttpServletRequest; import java.beans.Transient; import java.io.InputStream; import java.util.ArrayList; -import java.util.Date; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; @@ -74,7 +75,8 @@ public class UserServiceImpl implements UserService { if (userMapper.existsByEmail(email)) { throw new MyException(ResponseEnum.USERNAME_HAS_EXIST); } - boolean b = userMapper.addUser(email, MD5Util.getMD5(password)) == 1; + User user = new User(email, MD5Util.getMD5(password)); + boolean b = userMapper.addUser(user) == 1; if (b) { String verifyId = UUID.randomUUID().toString().replaceAll("-", ""); redisUtil.setEx(email + "-verify", verifyId, 2, TimeUnit.DAYS); @@ -116,7 +118,7 @@ public class UserServiceImpl implements UserService { } if (user.getPwd().equals(MD5Util.getMD5(loginReq.getPassword()))) { logger.info("====> {} 进行权限认证 状态:登录成功 <====", loginReq.getEmail()); - userMapper.updateLoginTime(loginReq.getEmail(), new Date()); + userMapper.updateLoginTime(loginReq.getEmail()); redisUtil.delete(loginReq.getEmail() + "-passwordWrongTime"); // redis 标记 redisUserUtil.set(user, loginReq.getIsRememberMe()); @@ -137,7 +139,7 @@ public class UserServiceImpl implements UserService { redisUtil.setEx(loginReq.getEmail() + "-passwordWrongTime", count + "", 2, TimeUnit.HOURS); throw new MyException(ResponseEnum.LOGIN_FAILURE); } - UserModel trans = trans(user); + UserModel trans = ModalTrans.user(user); trans.setToken(token); return trans; @@ -164,7 +166,7 @@ public class UserServiceImpl implements UserService { userMapper.updateInfo(desc, displayName, user.getId()); redisUserUtil.set(user); - return trans(user); + return ModalTrans.user(user); } @Override @@ -176,20 +178,6 @@ public class UserServiceImpl implements UserService { return role; } - @Override - public User getUserInfoByEmail(String email) { - User user = userMapper.findByEmail(email); - if (user == null) { - throw new MyException(ResponseEnum.USER_NOT_EXIST); - } - return user; - } - - @Override - public String getAvatarImg(long id) { - return userMapper.getAvatarImgUrlById(id); - } - @Override public Object updateUserAavatarImg(InputStream is, String mime) { User user = redisUserUtil.get(); @@ -203,7 +191,7 @@ public class UserServiceImpl implements UserService { @Override public UserModel getUserInfoBySession() { User user = redisUserUtil.get(); - return trans(user); + return ModalTrans.user(user); } @Override @@ -211,18 +199,6 @@ public class UserServiceImpl implements UserService { return userMapper.existsByEmail(email); } - @Override - public String getNameById(long id) { - String name = userMapper.getDisPlayName(id); - if (name == null) { - name = userMapper.getEmail(id); - if (name == null) { - throw new MyException(ResponseEnum.USER_NOT_EXIST); - } - } - return name; - } - /** * 找回密码 */ @@ -254,7 +230,6 @@ public class UserServiceImpl implements UserService { return "发送成功!"; } - //TODO @Override public Object sendVerifyEmail(String email) { if (!RegexUtil.emailMatch(email)) { @@ -366,14 +341,12 @@ public class UserServiceImpl implements UserService { } @Override - public PageInfo getUserList(Integer page, Integer count) { + public PageData getUserList(Integer page, Integer count) { PageHelper.startPage(page, count); List all = userMapper.findAll(); - PageInfo pageInfo = PageInfo.of(all); List modelList = new ArrayList<>(); - all.forEach(user -> modelList.add(trans(user))); - pageInfo.setList(modelList); - return pageInfo; + all.forEach(user -> modelList.add(ModalTrans.user(user))); + return new PageData(PageInfo.of(all), modelList); } @Override @@ -402,8 +375,7 @@ public class UserServiceImpl implements UserService { user.setPwd(MD5Util.getMD5(userReq.getPwd())); } if (userReq.getRole() != null) { - // TODO:用enum存放角色分类 - if ("user".equals(userReq.getRole()) || "admin".equals(userReq.getRole())) { + if (RoleEnum.USER_ROLE.getRoleName().equals(userReq.getRole()) || RoleEnum.ADMIN_ROLE.getRoleName().equals(userReq.getRole())) { user.setRole(userReq.getRole()); } else { throw new MyException(ResponseEnum.PARAMETERS_ERROR); @@ -413,7 +385,6 @@ public class UserServiceImpl implements UserService { if (!RegexUtil.emailMatch(userReq.getEmail())) { throw new MyException(ResponseEnum.PARAMETERS_EMAIL_ERROR); } - // TODO :: 邮件提醒 user.setEmail(userReq.getEmail()); } // 数据写入 @@ -425,7 +396,7 @@ public class UserServiceImpl implements UserService { redisUserUtil.set(user); } logger.info("修改了用户 [id={}] 的用户的资料", userReq.getId()); - return trans(user); + return ModalTrans.user(user); } @Override @@ -444,19 +415,6 @@ public class UserServiceImpl implements UserService { throw new MyException(ResponseEnum.PWD_NOT_SAME); } userMapper.updatePwd(user.getEmail(), MD5Util.getMD5(newPwd)); - return trans(userMapper.findByEmail(user.getEmail())); - } - - private UserModel trans(User u) { - UserModel user = new UserModel(); - user.setId(u.getId()); - user.setAvatarImgUrl(u.getAvatarImgUrl() == null ? null : "http://cdn.celess.cn/" + u.getAvatarImgUrl()); - user.setEmail(u.getEmail()); - user.setDesc(u.getDesc()); - user.setDisplayName(u.getDisplayName() == null ? u.getEmail() : u.getDisplayName()); - user.setEmailStatus(u.getEmailStatus()); - user.setRecentlyLandedDate(DateFormatUtil.get(u.getRecentlyLandedDate())); - user.setRole(u.getRole()); - return user; + return ModalTrans.user(userMapper.findByEmail(user.getEmail())); } } diff --git a/src/main/java/cn/celess/blog/util/ModalTrans.java b/src/main/java/cn/celess/blog/util/ModalTrans.java index c77e15a..a5cbdd8 100644 --- a/src/main/java/cn/celess/blog/util/ModalTrans.java +++ b/src/main/java/cn/celess/blog/util/ModalTrans.java @@ -40,6 +40,11 @@ public class ModalTrans { public static UserModel user(User user) { UserModel userModel = new UserModel(); BeanUtils.copyProperties(user, userModel); + userModel.setAvatarImgUrl(user.getAvatarImgUrl() == null || user.getAvatarImgUrl().length() == 0 ? + null : + "http://cdn.celess.cn/" + user.getAvatarImgUrl()); + userModel.setDisplayName(user.getDisplayName() == null ? user.getEmail() : user.getDisplayName()); + userModel.setRecentlyLandedDate(DateFormatUtil.get(user.getRecentlyLandedDate())); return userModel; } diff --git a/src/test/java/cn/celess/blog/controller/UserControllerTest.java b/src/test/java/cn/celess/blog/controller/UserControllerTest.java index c4eb7f2..1691c3a 100644 --- a/src/test/java/cn/celess/blog/controller/UserControllerTest.java +++ b/src/test/java/cn/celess/blog/controller/UserControllerTest.java @@ -2,12 +2,12 @@ package cn.celess.blog.controller; import cn.celess.blog.BaseTest; import cn.celess.blog.entity.User; +import cn.celess.blog.entity.model.PageData; import cn.celess.blog.entity.model.UserModel; import cn.celess.blog.entity.request.LoginReq; import cn.celess.blog.entity.request.UserReq; import cn.celess.blog.mapper.UserMapper; import cn.celess.blog.util.MD5Util; -import com.github.pagehelper.PageInfo; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.junit.Test; @@ -50,8 +50,7 @@ public class UserControllerTest extends BaseTest { @Test public void registration() { - // 自行手动测试! - // TODO : + // ignore } @Test @@ -136,7 +135,8 @@ public class UserControllerTest extends BaseTest { String s = UUID.randomUUID().toString(); String email = s.substring(s.length() - 4) + "@celess.cn"; String pwd = MD5Util.getMD5("123456789"); - int i1 = userMapper.addUser(email, pwd); + User user = new User(email, pwd); + int i1 = userMapper.addUser(user); if (i1 == 0) { continue; } @@ -177,7 +177,8 @@ public class UserControllerTest extends BaseTest { public void updateInfoByAdmin() throws Exception { UserReq userReq = new UserReq(); String email = UUID.randomUUID().toString().substring(0, 4) + "@celess.cn"; - userMapper.addUser(email, MD5Util.getMD5("123456789")); + User user = new User(email, MD5Util.getMD5("123456789")); + userMapper.addUser(user); User userByDb = userMapper.findByEmail(email); userReq.setId(userByDb.getId()); userReq.setPwd(UUID.randomUUID().toString().replaceAll("-", "").substring(0, 10)); @@ -194,12 +195,12 @@ public class UserControllerTest extends BaseTest { .andDo(result -> { JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString()); assertEquals(SUCCESS.getCode(), object.getInt(Code)); - UserModel user = (UserModel) JSONObject.toBean(object.getJSONObject(Result), UserModel.class); - assertEquals(userReq.getId(), user.getId()); - assertEquals(userReq.getRole(), user.getRole()); - assertEquals(userReq.getEmail(), user.getEmail()); - assertEquals(userReq.getDesc(), user.getDesc()); - assertEquals(userReq.getDisplayName(), user.getDisplayName()); + UserModel userModel = (UserModel) JSONObject.toBean(object.getJSONObject(Result), UserModel.class); + assertEquals(userReq.getId(), userModel.getId()); + assertEquals(userReq.getRole(), userModel.getRole()); + assertEquals(userReq.getEmail(), userModel.getEmail()); + assertEquals(userReq.getDesc(), userModel.getDesc()); + assertEquals(userReq.getDisplayName(), userModel.getDisplayName()); }); } @@ -217,14 +218,12 @@ public class UserControllerTest extends BaseTest { assertNotNull(object.getJSONObject(Result)); // 判断pageInfo是否包装完全 JSONObject resultJson = JSONObject.fromObject(object.getJSONObject(Result)); - PageInfo pageInfo = (PageInfo) JSONObject.toBean(resultJson, PageInfo.class); - assertNotEquals(0, pageInfo.getTotal()); - assertNotEquals(0, pageInfo.getStartRow()); - assertNotEquals(0, pageInfo.getEndRow()); - assertEquals(1, pageInfo.getPageNum()); - assertEquals(10, pageInfo.getPageSize()); + PageData pageData = (PageData) JSONObject.toBean(resultJson, PageData.class); + assertNotEquals(0, pageData.getTotal()); + assertEquals(1, pageData.getPageNum()); + assertEquals(10, pageData.getPageSize()); // 内容完整 - for (Object user : pageInfo.getList()) { + for (Object user : pageData.getList()) { UserModel u = (UserModel) JSONObject.toBean(JSONObject.fromObject(user), UserModel.class); assertNotNull(u.getId()); assertNotNull(u.getEmail()); @@ -254,7 +253,7 @@ public class UserControllerTest extends BaseTest { @Test public void setPwd() throws Exception { String email = UUID.randomUUID().toString().substring(0, 4) + "@celess.cn"; - assertEquals(1, userMapper.addUser(email, MD5Util.getMD5("1234567890"))); + assertEquals(1, userMapper.addUser(new User(email, MD5Util.getMD5("1234567890")))); LoginReq req = new LoginReq(); req.setEmail(email); req.setPassword("1234567890"); From aa882406d0f7cccc9e3cee587e911ef8c8dfc3e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Tue, 26 May 2020 12:34:35 +0800 Subject: [PATCH 24/33] =?UTF-8?q?Service,dao=E5=B1=82,=E8=A7=86=E5=9B=BE,?= =?UTF-8?q?=E6=A8=A1=E5=9E=8B=E4=BF=AE=E6=94=B9=20=20=20=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- newBlog.sql | 64 +++-- .../blog/controller/CommentController.java | 60 ++--- .../cn/celess/blog/enmu/ResponseEnum.java | 3 +- .../blog/entity/model/CommentModel.java | 26 +- .../blog/entity/request/CommentReq.java | 7 +- .../cn/celess/blog/mapper/CommentMapper.java | 2 + .../celess/blog/service/CommentService.java | 47 ++-- .../serviceimpl/CommentServiceImpl.java | 155 +++++------ .../java/cn/celess/blog/util/ModalTrans.java | 24 ++ src/main/resources/mapper/CommentMapper.xml | 12 +- .../controller/CommentControllerTest.java | 245 +++--------------- 11 files changed, 219 insertions(+), 426 deletions(-) diff --git a/newBlog.sql b/newBlog.sql index bfaaafd..fa4cf14 100644 --- a/newBlog.sql +++ b/newBlog.sql @@ -137,30 +137,42 @@ where article.a_id = article_tag.a_id and category.is_category = true and article.a_author_id = user.u_id; -CREATE VIEW commentView - (commentId, pagePath, content, date, status, pid, - fromAuthorId, fromAuthorEmail, fromAuthorDisplayName, fromAuthorAvatar, toAuthorId, - toAuthorEmail, toAuthorDisplayName, toAuthorAvatar, isDelete - ) -as -select comment.co_id as commentId, - comment.co_page_path as pagePath, - comment.co_content as content, - comment.co_date as date, - comment.co_status as status, - comment.co_pid as pid, - comment.co_from_author_id as fromAuthorId, - userFrom.u_email as fromAuthorEmail, - userFrom.u_display_name as fromAuthorDisplayName, - userFrom.u_avatar as fromAuthorAvatar, - comment.co_to_author_id as toAuthorId, - userTo.u_email as toAuthorEmail, - userTo.u_display_name as toAuthorDisplayName, - userTo.u_avatar as toAuthorAvatar, - comment.is_delete as isDelete -from comment, - user as userFrom, - user as userTo -where comment.co_from_author_id = userFrom.u_id - and comment.co_to_author_id = userTo.u_id; + +CREATE VIEW commentView + (commentId, pagePath, content, date, status, pid, toAuthorId, toAuthorEmail, toAuthorDisplayName, + toAuthorAvatar, fromAuthorId, fromAuthorEmail, fromAuthorDisplayName, + fromAuthorAvatar, isDelete) +as +select cuT.co_id as commentId, + cuT.co_page_path as pagePath, + cuT.co_content as content, + cuT.co_date as date, + cuT.co_status as status, + cuT.co_pid as pid, + cuT.co_to_author_id as toAuthorId, + cuT.toEmail as toAuthorEmail, + cuT.toDisplayName as toAuthorDisplayName, + cuT.toAvatar as toAuthorAvatar, + userFrom.u_id as fromAuthorId, + userFrom.u_email as fromAuthorEmail, + userFrom.u_display_name as fromAuthorDisplayName, + userFrom.u_avatar as fromAuthorAvatar, + cuT.is_delete as isDelete +from (select comment.co_id, + comment.co_page_path, + comment.co_content, + comment.co_date, + comment.co_status, + comment.co_pid, + comment.co_from_author_id, + comment.co_to_author_id, + userTo.u_email as toEmail, + userTo.u_display_name as toDisplayName, + userTo.u_avatar as toAvatar, + comment.is_delete + from comment + left join user userTo on (comment.co_to_author_id = userTo.u_id) + ) as cuT, + user as userFrom +where cuT.co_from_author_id = userFrom.u_id; diff --git a/src/main/java/cn/celess/blog/controller/CommentController.java b/src/main/java/cn/celess/blog/controller/CommentController.java index dff5808..8234490 100644 --- a/src/main/java/cn/celess/blog/controller/CommentController.java +++ b/src/main/java/cn/celess/blog/controller/CommentController.java @@ -40,58 +40,40 @@ public class CommentController { } /** - * 获取所有的一级评论 + * 获取所有的评论 * - * @param articleId 文章id - * @param count 单页数据量 - * @param page 页码 + * @param pagePath pagePath + * @param count 单页数据量 + * @param page 页码 * @return Response */ @GetMapping("/comments") - public Response commentsOfArticle(@RequestParam("articleId") long articleId, + public Response commentsOfArticle(@RequestParam("pagePath") String pagePath, + @RequestParam(value = "pid", required = false, defaultValue = "-1") long pid, @RequestParam(value = "count", required = false, defaultValue = "10") int count, @RequestParam(value = "page", required = false, defaultValue = "1") int page) { - return ResponseUtil.success(commentService.retrievePageByArticle(articleId, -1, page, count)); + return ResponseUtil.success(commentService.retrievePageByPageAndPid(pagePath, pid, page, count)); } /** * 通过pid获取数据 * - * @param pid - * @return + * @param pagePath pagePath + * @param count count + * @param page page + * @return Response */ - @GetMapping("/comment/pid/{pid}") - public Response retrievePage(@PathVariable("pid") long pid) { - return ResponseUtil.success(commentService.retrievePageByPid(pid)); + @GetMapping("/comment/pagePath/{pagePath}") + public Response retrievePage(@PathVariable("pagePath") String pagePath, + @RequestParam(value = "count", required = false, defaultValue = "10") int count, + @RequestParam(value = "page", required = false, defaultValue = "1") int page) { + return ResponseUtil.success(commentService.retrievePage(pagePath, page, count)); } - /** - * 获取所以的一级留言 - * - * @param count - * @param page - * @return - */ - @GetMapping("/leaveMsg") - public Response retrievePageOfLeaveMsg(@RequestParam(value = "count", required = false, defaultValue = "10") int count, - @RequestParam(value = "page", required = false, defaultValue = "1") int page) { - return ResponseUtil.success(commentService.retrievePageByTypeAndPid(false, -1, page, count)); + @GetMapping("/user/comment/pagePath/{pagePath}") + public Response userComment(@PathVariable("pagePath") String pagePath, + @RequestParam(value = "count", required = false, defaultValue = "10") int count, + @RequestParam(value = "page", required = false, defaultValue = "1") int page) { + return ResponseUtil.success(commentService.retrievePageByAuthor(pagePath, page, count)); } - - @GetMapping("/admin/comment/type/{type}") - public Response retrievePageAdmin( - @PathVariable("type") int isComment, - @RequestParam(value = "count", required = false, defaultValue = "10") int count, - @RequestParam(value = "page", required = false, defaultValue = "1") int page) { - return ResponseUtil.success(commentService.retrievePageByType(1 == isComment, page, count)); - } - - @GetMapping("/user/comment/type/{type}") - public Response retrievePageByAuthor( - @PathVariable(value = "type") int isComment, - @RequestParam(value = "count", required = false, defaultValue = "10") int count, - @RequestParam(value = "page", required = false, defaultValue = "1") int page) { - return ResponseUtil.success(commentService.retrievePageByAuthor(1 == isComment, page, count)); - } - } diff --git a/src/main/java/cn/celess/blog/enmu/ResponseEnum.java b/src/main/java/cn/celess/blog/enmu/ResponseEnum.java index e26c48a..d61c5bf 100644 --- a/src/main/java/cn/celess/blog/enmu/ResponseEnum.java +++ b/src/main/java/cn/celess/blog/enmu/ResponseEnum.java @@ -11,6 +11,8 @@ public enum ResponseEnum { FAILURE(-1, "失败"), ERROR(-2, "错误"), + DATA_IS_DELETED(1000, "数据已被删除"), + //文章类 ARTICLE_NOT_EXIST(2010, "文章不存在"), ARTICLE_HAS_EXIST(2020, "文章已存在"), @@ -68,7 +70,6 @@ public enum ResponseEnum { PARAMETERS_QQ_ERROR(8540, "QQ格式错误"), PARAMETERS_PWD_ERROR(8550, "密码格式错误"), VERIFY_OUT(8400, "已经验证过了"); - private int code; private String msg; diff --git a/src/main/java/cn/celess/blog/entity/model/CommentModel.java b/src/main/java/cn/celess/blog/entity/model/CommentModel.java index 1fa68d6..b4541b6 100644 --- a/src/main/java/cn/celess/blog/entity/model/CommentModel.java +++ b/src/main/java/cn/celess/blog/entity/model/CommentModel.java @@ -1,5 +1,6 @@ package cn.celess.blog.entity.model; +import cn.celess.blog.entity.User; import lombok.Getter; import lombok.Setter; @@ -14,46 +15,31 @@ import java.util.List; public class CommentModel { private long id; - /** - * 是评论还是留言 0:评论 其他(1):留言 - */ - private boolean isComment; + private UserModel fromUser; - private String authorName; - - private String authorAvatarImgUrl; + private UserModel toUser; /** * 内容 */ private String content; - /** - * 文章ID - */ - private long articleID; - /** * 文章标题 */ - private String articleTitle; + private String pagePath; /** * 发布日期 */ private String date; - /** - * 回应着ID 默认为顶级回复 - */ - private String responseId = ""; - /** * 评论的父ID */ - private long pid = -1; + private Long pid; private List respComment; - + private int status; } diff --git a/src/main/java/cn/celess/blog/entity/request/CommentReq.java b/src/main/java/cn/celess/blog/entity/request/CommentReq.java index a310c30..c322326 100644 --- a/src/main/java/cn/celess/blog/entity/request/CommentReq.java +++ b/src/main/java/cn/celess/blog/entity/request/CommentReq.java @@ -9,9 +9,8 @@ import lombok.Data; @Data public class CommentReq { private Long id; - private Boolean comment; private String content; - private Long pid; - private Long articleID; - private String responseId; + private long pid = -1; + private String pagePath; + private long toUserId = -1; } diff --git a/src/main/java/cn/celess/blog/mapper/CommentMapper.java b/src/main/java/cn/celess/blog/mapper/CommentMapper.java index c79cd84..7169479 100644 --- a/src/main/java/cn/celess/blog/mapper/CommentMapper.java +++ b/src/main/java/cn/celess/blog/mapper/CommentMapper.java @@ -34,6 +34,8 @@ public interface CommentMapper { List findAllByPagePath(String pagePath); + List findAllByPagePathAndFromUser(String pagePath,long userId); + List findAllByPagePathAndPid(String pagePath, long pid); long countByPagePath(String pagePath); diff --git a/src/main/java/cn/celess/blog/service/CommentService.java b/src/main/java/cn/celess/blog/service/CommentService.java index d8a6841..3d5d560 100644 --- a/src/main/java/cn/celess/blog/service/CommentService.java +++ b/src/main/java/cn/celess/blog/service/CommentService.java @@ -1,6 +1,7 @@ package cn.celess.blog.service; import cn.celess.blog.entity.model.CommentModel; +import cn.celess.blog.entity.model.PageData; import cn.celess.blog.entity.request.CommentReq; import com.github.pagehelper.PageInfo; import org.springframework.stereotype.Service; @@ -40,17 +41,17 @@ public interface CommentService { /** * 分页获取数据 * - * @param isComment true:评论 false:留言 - * @param count 单页数据量 - * @param page 数据页 + * @param pagePath pagePath + * @param count 单页数据量 + * @param page 数据页 * @return 分页数据 */ - PageInfo retrievePage(Boolean isComment, int page, int count); + PageData retrievePage(String pagePath, int page, int count); /** * 通过pid获取数据 * - * @param pid 父id + * @param pid 父id * @return 分页数据 */ List retrievePageByPid(long pid); @@ -59,43 +60,33 @@ public interface CommentService { /** * 根据评论者获取数据 * - * @param isComment true:评论 false:留言 - * @param count 单页数据量 - * @param page 数据页 + * @param pagePath pagePath + * @param count 单页数据量 + * @param page 数据页 * @return 分页数据 */ - PageInfo retrievePageByAuthor(Boolean isComment, int page, int count); + PageData retrievePageByAuthor(String pagePath, int page, int count); - /** - * 根据文章获取数据 - * - * @param articleID 文章id - * @param pid 父id - * @param count 单页数据量 - * @param page 数据页 - * @return 分页数据 - */ - PageInfo retrievePageByArticle(long articleID, long pid, int page, int count); /** * 根据数据的type和pid获取数据 * - * @param isComment true:评论 false:留言 - * @param pid 父id - * @param count 单页数据量 - * @param page 数据页 + * @param pagePath pagePath + * @param pid 父id + * @param count 单页数据量 + * @param page 数据页 * @return 分页数据 */ - PageInfo retrievePageByTypeAndPid(Boolean isComment, int pid, int page, int count); + PageData retrievePageByPageAndPid(String pagePath, long pid, int page, int count); /** * 根据type获取数据 * - * @param isComment true:评论 false:留言 - * @param count 单页数据量 - * @param page 数据页 + * @param pagePath pagePath + * @param count 单页数据量 + * @param page 数据页 * @return 分页数据 */ - PageInfo retrievePageByType(Boolean isComment, int page, int count); + PageData retrievePageByPage(String pagePath, int page, int count); } diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/CommentServiceImpl.java b/src/main/java/cn/celess/blog/service/serviceimpl/CommentServiceImpl.java index af9cedb..a8b6d2b 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/CommentServiceImpl.java +++ b/src/main/java/cn/celess/blog/service/serviceimpl/CommentServiceImpl.java @@ -2,18 +2,22 @@ package cn.celess.blog.service.serviceimpl; import cn.celess.blog.enmu.ResponseEnum; import cn.celess.blog.entity.Comment; +import cn.celess.blog.entity.User; import cn.celess.blog.entity.model.CommentModel; +import cn.celess.blog.entity.model.PageData; import cn.celess.blog.entity.request.CommentReq; import cn.celess.blog.exception.MyException; import cn.celess.blog.mapper.ArticleMapper; import cn.celess.blog.mapper.CommentMapper; +import cn.celess.blog.mapper.UserMapper; import cn.celess.blog.service.CommentService; import cn.celess.blog.service.UserService; import cn.celess.blog.util.DateFormatUtil; +import cn.celess.blog.util.ModalTrans; import cn.celess.blog.util.RedisUserUtil; -import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; +import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -31,7 +35,7 @@ public class CommentServiceImpl implements CommentService { @Autowired CommentMapper commentMapper; @Autowired - UserService userService; + UserMapper userMapper; @Autowired ArticleMapper articleMapper; @Autowired @@ -41,52 +45,43 @@ public class CommentServiceImpl implements CommentService { @Override public CommentModel create(CommentReq reqBody) { - if (reqBody == null) { throw new MyException(ResponseEnum.PARAMETERS_ERROR); } - long authorID = redisUserUtil.get().getId(); + User user = redisUserUtil.get(); Comment pComment = null; - if (reqBody.getPid() != null && reqBody.getPid() != -1) { + if (reqBody.getPid() != -1) { pComment = commentMapper.findCommentById(reqBody.getPid()); } - if (reqBody.getPid() == null) { - reqBody.setPid(-1L); - } //不是一级评论 if (reqBody.getPid() != -1 && pComment == null) { //父评论不存在 throw new MyException(ResponseEnum.PARAMETERS_ERROR); } Comment comment = new Comment(); - comment.setAuthorID(authorID); - comment.setType(reqBody.getComment()); - if (reqBody.getComment()) { - //若为评论 - if (reqBody.getArticleID() <= 0) { - throw new MyException(ResponseEnum.PARAMETERS_ERROR); - } - comment.setArticleID(reqBody.getArticleID()); - } else { - comment.setArticleID(-1L); + comment.setFromUser(user); + User userTo = new User(); + userTo.setId(-1L); + if (reqBody.getToUserId() != -1) { + userTo = userMapper.findById(reqBody.getToUserId()); + comment.setToUser(userTo); } - comment.setContent(reqBody.getContent()); - comment.setPid(reqBody.getPid()); - comment.setDate(new Date()); - comment.setResponseId(""); + comment.setToUser(userTo); + userMapper.findById(reqBody.getToUserId()); + BeanUtils.copyProperties(reqBody, comment); commentMapper.insert(comment); - if (reqBody.getPid() != -1) { - commentMapper.updateResponder(pComment.getResponseId() + comment.getId() + ",", reqBody.getPid()); - } - return trans(comment); + return ModalTrans.comment(commentMapper.findCommentById(comment.getId())); } @Override public boolean delete(long id) { - boolean b = commentMapper.existsById(id); - if (!b) { + Comment b = commentMapper.findCommentById(id); + if (b == null ) { throw new MyException(ResponseEnum.COMMENT_NOT_EXIST); } + if(b.isDelete()){ + throw new MyException(ResponseEnum.DATA_IS_DELETED); + } commentMapper.delete(id); return true; } @@ -101,86 +96,54 @@ public class CommentServiceImpl implements CommentService { commentMapper.updateContent(reqBody.getContent(), reqBody.getId()); comment.setContent(reqBody.getContent()); } - if (!comment.getResponseId().equals(reqBody.getResponseId())) { - commentMapper.updateResponder(reqBody.getResponseId(), reqBody.getId()); - comment.setResponseId(reqBody.getResponseId()); - } - return trans(comment); + return ModalTrans.comment(comment); } - @Override - public PageInfo retrievePage(Boolean isComment, int page, int count) { + public PageData retrievePage(String pagePath, int page, int count) { PageHelper.startPage(page, count); - List commentList = commentMapper.findAllByType(isComment); - return pageTrans(commentList); + List list = commentMapper.findAllByPagePath(pagePath); + return pageTrans(list); } @Override public List retrievePageByPid(long pid) { - List commentList = commentMapper.findAllByPId(pid); + List allByPagePath = commentMapper.findAllByPid(pid); + List commentModels = new ArrayList<>(); + allByPagePath.forEach(comment -> commentModels.add(ModalTrans.comment(comment))); + return commentModels; + } + + @Override + public PageData retrievePageByAuthor(String pagePath, int page, int count) { + User user = redisUserUtil.get(); + PageHelper.startPage(page, count); + List list = commentMapper.findAllByPagePathAndFromUser(pagePath, user.getId()); + return pageTrans(list); + } + + @Override + public PageData retrievePageByPageAndPid(String pagePath, long pid, int page, int count) { + PageHelper.startPage(page, count); + List list = commentMapper.findAllByPagePathAndPid(pagePath, pid); + return pageTrans(list); + } + + @Override + public PageData retrievePageByPage(String pagePath, int page, int count) { + PageHelper.startPage(page, count); + List list = commentMapper.findAllByPagePathAndPid(pagePath, -1); + return pageTrans(list); + } + + private PageData pageTrans(List commentList) { + PageInfo p = PageInfo.of(commentList); List modelList = new ArrayList<>(); - commentList.forEach(m -> modelList.add(trans(m))); - return modelList; - } - - @Override - public PageInfo retrievePageByArticle(long articleID, long pid, int page, int count) { - PageHelper.startPage(page, count); - List commentList = commentMapper.findAllByArticleIDAndPId(articleID, pid); - return pageTrans(commentList); - } - - @Override - public PageInfo retrievePageByTypeAndPid(Boolean isComment, int pid, int page, int count) { - PageHelper.startPage(page, count); - List commentList = commentMapper.findCommentsByTypeAndPId(isComment, pid); - return pageTrans(commentList); - } - - @Override - public PageInfo retrievePageByAuthor(Boolean isComment, int page, int count) { - PageHelper.startPage(page, count); - List commentList = commentMapper.findAllByAuthorIDAndType(redisUserUtil.get().getId(), isComment); - return pageTrans(commentList); - } - - - @Override - public PageInfo retrievePageByType(Boolean isComment, int page, int count) { - PageHelper.startPage(page, count); - List commentList = commentMapper.findAllByType(isComment); - return pageTrans(commentList); - } - - private CommentModel trans(Comment comment) { - CommentModel commentModel = new CommentModel(); - commentModel.setId(comment.getId()); - commentModel.setComment(comment.getType()); - commentModel.setContent(comment.getContent()); - commentModel.setArticleID(comment.getArticleID()); - commentModel.setDate(DateFormatUtil.get(comment.getDate())); - commentModel.setResponseId(comment.getResponseId()); - commentModel.setPid(comment.getPid()); - commentModel.setAuthorName(userService.getNameById(comment.getAuthorID())); - commentModel.setAuthorAvatarImgUrl("http://cdn.celess.cn/" + userService.getAvatarImg(comment.getAuthorID())); - - if (comment.getType() && commentModel.getArticleID() > 0) { - commentModel.setArticleTitle(articleMapper.getTitleById(comment.getArticleID())); - } - return commentModel; - } - - private PageInfo pageTrans(List commentList) { - PageInfo p = new PageInfo(commentList); - List modelList = new ArrayList<>(); - commentList.forEach(l -> { - CommentModel model = trans(l); + CommentModel model = ModalTrans.comment(l); model.setRespComment(this.retrievePageByPid(model.getId())); modelList.add(model); }); - p.setList(modelList); - return p; + return new PageData(p, modelList); } } diff --git a/src/main/java/cn/celess/blog/util/ModalTrans.java b/src/main/java/cn/celess/blog/util/ModalTrans.java index a5cbdd8..9b58ab7 100644 --- a/src/main/java/cn/celess/blog/util/ModalTrans.java +++ b/src/main/java/cn/celess/blog/util/ModalTrans.java @@ -38,6 +38,9 @@ public class ModalTrans { public static UserModel user(User user) { + if (user == null || user.getId() == -1) { + return null; + } UserModel userModel = new UserModel(); BeanUtils.copyProperties(user, userModel); userModel.setAvatarImgUrl(user.getAvatarImgUrl() == null || user.getAvatarImgUrl().length() == 0 ? @@ -49,6 +52,9 @@ public class ModalTrans { } public static CategoryModel category(Category category) { + if (category == null) { + return null; + } CategoryModel model = new CategoryModel(); BeanUtils.copyProperties(category, model); return model; @@ -56,6 +62,9 @@ public class ModalTrans { public static TagModel tag(Tag tag) { + if (tag == null) { + return null; + } TagModel model = new TagModel(); BeanUtils.copyProperties(tag, model); return model; @@ -63,10 +72,25 @@ public class ModalTrans { public static WebUpdateModel webUpdate(WebUpdate update) { + if (update == null) { + return null; + } WebUpdateModel model = new WebUpdateModel(); model.setId(update.getId()); model.setInfo(update.getUpdateInfo()); model.setTime(DateFormatUtil.get(update.getUpdateTime())); return model; } + + public static CommentModel comment(Comment comment) { + if (comment == null) { + return null; + } + CommentModel model = new CommentModel(); + BeanUtils.copyProperties(comment, model); + model.setFromUser(user(comment.getFromUser())); + model.setToUser(user(comment.getToUser())); + model.setDate(DateFormatUtil.get(comment.getDate())); + return model; + } } diff --git a/src/main/resources/mapper/CommentMapper.xml b/src/main/resources/mapper/CommentMapper.xml index 6c7026e..042c078 100644 --- a/src/main/resources/mapper/CommentMapper.xml +++ b/src/main/resources/mapper/CommentMapper.xml @@ -68,7 +68,7 @@ + + select count(*) - from article where is_delete = false; + from article + where is_delete = false; diff --git a/src/test/java/cn/celess/blog/controller/CommentControllerTest.java b/src/test/java/cn/celess/blog/controller/CommentControllerTest.java index 24b07d1..19df58b 100644 --- a/src/test/java/cn/celess/blog/controller/CommentControllerTest.java +++ b/src/test/java/cn/celess/blog/controller/CommentControllerTest.java @@ -3,24 +3,18 @@ package cn.celess.blog.controller; import cn.celess.blog.BaseTest; import cn.celess.blog.entity.Article; import cn.celess.blog.entity.Comment; +import cn.celess.blog.entity.User; import cn.celess.blog.entity.model.CommentModel; import cn.celess.blog.entity.request.CommentReq; import cn.celess.blog.mapper.ArticleMapper; import cn.celess.blog.mapper.CommentMapper; import cn.celess.blog.mapper.UserMapper; -import com.github.pagehelper.PageInfo; -import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.result.MockMvcResultHandlers; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; import java.util.UUID; -import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.*; import static cn.celess.blog.enmu.ResponseEnum.*; @@ -30,19 +24,19 @@ public class CommentControllerTest extends BaseTest { @Autowired ArticleMapper articleMapper; @Autowired + UserMapper userMapper; + @Autowired CommentMapper commentMapper; @Test public void addOne() throws Exception { + Article article = articleMapper.getLastestArticle(); CommentReq commentReq = new CommentReq(); - // 测试留言 - commentReq.setArticleID(null); - commentReq.setComment(false); + commentReq.setPagePath("/article/" + article.getId()); commentReq.setContent(UUID.randomUUID().toString()); commentReq.setPid(-1L); - commentReq.setResponseId(null); + commentReq.setToUserId(-1L); String token = userLogin(); - CommentModel PC = null; mockMvc.perform(post("/user/comment/create") .contentType(MediaType.APPLICATION_JSON_UTF8) .content(JSONObject.fromObject(commentReq).toString()) @@ -52,22 +46,19 @@ public class CommentControllerTest extends BaseTest { assertEquals(SUCCESS.getCode(), object.getInt(Code)); CommentModel model = (CommentModel) JSONObject.toBean(object.getJSONObject(Result), CommentModel.class); assertNotEquals(0, model.getId()); - assertEquals(commentReq.getPid().longValue(), model.getPid()); - assertEquals(-1, model.getPid()); - assertEquals(commentReq.getComment(), model.isComment()); + assertEquals(commentReq.getPid(), model.getPid().longValue()); + assertEquals(-1, model.getPid().longValue()); assertEquals(commentReq.getContent(), model.getContent()); assertNotNull(model.getDate()); - assertNotNull(model.getAuthorName()); - assertNotNull(model.getAuthorAvatarImgUrl()); + assertNotNull(model.getFromUser()); + assertNull(model.getToUser()); }); - Article article = articleMapper.getLastestArticle(); - // 测试评论 - commentReq.setArticleID(article.getId()); - commentReq.setComment(true); + + commentReq.setPagePath("/article/" + article.getId()); commentReq.setContent(UUID.randomUUID().toString()); commentReq.setPid(-1L); - commentReq.setResponseId(null); + commentReq.setToUserId(2); mockMvc.perform(post("/user/comment/create") .contentType(MediaType.APPLICATION_JSON_UTF8) .content(JSONObject.fromObject(commentReq).toString()) @@ -78,58 +69,50 @@ public class CommentControllerTest extends BaseTest { CommentModel model = (CommentModel) JSONObject.toBean(object.getJSONObject(Result), CommentModel.class); // 响应数据的完整性 assertNotEquals(0, model.getId()); - assertEquals(commentReq.getPid().longValue(), model.getPid()); - assertEquals(-1, model.getPid()); - assertEquals(commentReq.getComment(), model.isComment()); + assertEquals(commentReq.getPid(), model.getPid().longValue()); + assertEquals(-1, model.getPid().longValue()); assertEquals(commentReq.getContent(), model.getContent()); - assertEquals(commentReq.getArticleID().longValue(), model.getArticleID()); + assertEquals(commentReq.getPagePath(), "/article/" + article.getId()); assertNotNull(model.getDate()); - assertNotNull(model.getAuthorName()); - assertNotNull(model.getAuthorAvatarImgUrl()); + assertNotNull(model.getFromUser()); + assertNotNull(model.getToUser()); }); // 测试二级回复 Comment lastestComment = commentMapper.getLastestComment(); - commentReq.setArticleID(lastestComment.getArticleID()); - commentReq.setComment(lastestComment.getType()); + commentReq.setPagePath("/article/" + article.getId()); commentReq.setContent(UUID.randomUUID().toString()); commentReq.setPid(lastestComment.getId()); - commentReq.setResponseId(null); mockMvc.perform(post("/user/comment/create") .contentType(MediaType.APPLICATION_JSON_UTF8) .content(JSONObject.fromObject(commentReq).toString()) .header("Authorization", token) - ).andDo(MockMvcResultHandlers.print()).andDo(result -> { + ).andDo(result -> { JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString()); assertEquals(SUCCESS.getCode(), object.getInt(Code)); CommentModel model = (CommentModel) JSONObject.toBean(object.getJSONObject(Result), CommentModel.class); // 重新获取父评论信息 Comment pCommon = commentMapper.findCommentById(lastestComment.getId()); - assertEquals(pCommon.getId().longValue(), model.getPid()); - // 判断父评论中是否有写入当前新增的评论的id - String[] ids = pCommon.getResponseId().split(","); - boolean contain = false; - for (String id : ids) { - if (!id.isEmpty() && Long.parseLong(id) == model.getId()) { - contain = true; - break; - } - } - assertTrue(contain); + assertEquals(pCommon.getId(), model.getPid()); }); } @Test public void deleteTest() throws Exception { // 准备数据 - Comment c = new Comment(); - c.setArticleID(-1L); - c.setType(true); - c.setAuthorID(2L); - c.setDate(new Date()); - c.setPid(-1L); - commentMapper.insert(c); - Comment comment = commentMapper.getLastestComment(); + User from = userMapper.findByEmail("zh56462271@qq.com"); + assertNotNull(from); + User to = userMapper.findByEmail("a@celess.cn"); + assertNotNull(to); + + Comment comment = new Comment(); + comment.setContent(randomStr(8)); + comment.setFromUser(from); + comment.setToUser(to); + comment.setPagePath("/tags"); + comment.setPid(-1L); + commentMapper.insert(comment); + comment = commentMapper.findCommentById(comment.getId()); // 接口测试 long id = comment.getId(); assertNotEquals(0, id); @@ -141,7 +124,7 @@ public class CommentControllerTest extends BaseTest { }); mockMvc.perform(delete("/user/comment/del?id=" + id).header("Authorization", token)).andDo(result -> { JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString()); - assertEquals(COMMENT_NOT_EXIST.getCode(), object.getInt(Code)); + assertEquals(DATA_IS_DELETED.getCode(), object.getInt(Code)); }); } @@ -150,12 +133,8 @@ public class CommentControllerTest extends BaseTest { Comment comment = commentMapper.getLastestComment(); CommentReq commentReq = new CommentReq(); commentReq.setId(comment.getId()); - commentReq.setPid(comment.getPid()); commentReq.setContent(UUID.randomUUID().toString()); - commentReq.setArticleID(comment.getArticleID()); // 不合法数据 setResponseId - commentReq.setResponseId("xxxx"); - commentReq.setComment(comment.getType()); mockMvc.perform(put("/user/comment/update") .content(JSONObject.fromObject(commentReq).toString()) .contentType(MediaType.APPLICATION_JSON_UTF8) @@ -165,161 +144,7 @@ public class CommentControllerTest extends BaseTest { assertEquals(SUCCESS.getCode(), object.getInt(Code)); CommentModel c = (CommentModel) JSONObject.toBean(object.getJSONObject(Result), CommentModel.class); assertEquals(commentReq.getContent(), c.getContent()); - assertEquals(commentReq.getResponseId(), c.getResponseId()); - assertNotNull(c.getAuthorAvatarImgUrl()); - assertNotNull(c.getAuthorName()); - assertNotNull(c.getDate()); - assertNotEquals(0, c.getPid()); - assertNotEquals(0, c.getArticleID()); }); } - @Test - public void commentsOfArticle() throws Exception { - mockMvc.perform(get("/comments?articleId=3&page=1&count=10")).andDo(result -> { - JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString()); - assertEquals(SUCCESS.getCode(), object.getInt(Code)); - PageInfo pageInfo = (PageInfo) JSONObject.toBean(object.getJSONObject(Result), PageInfo.class); - assertNotEquals(0, pageInfo.getStartRow()); - assertNotEquals(0, pageInfo.getEndRow()); - assertEquals(1, pageInfo.getPageNum()); - assertEquals(10, pageInfo.getPageSize()); - pageInfo.getList().forEach(o -> { - CommentModel model = (CommentModel) JSONObject.toBean(JSONObject.fromObject(o), CommentModel.class); - assertEquals(3, model.getArticleID()); - assertNotNull(model.getDate()); - assertNotNull(model.getAuthorName()); - assertNotNull(model.getAuthorAvatarImgUrl()); - assertNotNull(model.getArticleTitle()); - assertNotNull(model.getContent()); - assertNotNull(model.getResponseId()); - }); - }); - } - - @Test - public void retrievePage() throws Exception { - long pid = -1; - mockMvc.perform(get("/comment/pid/" + pid)).andDo(result -> { - JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString()); - assertEquals(SUCCESS.getCode(), object.getInt(Code)); - JSONArray jsonArray = object.getJSONArray(Result); - assertNotEquals(0, jsonArray.size()); - jsonArray.forEach(o -> { - CommentModel model = (CommentModel) JSONObject.toBean(JSONObject.fromObject(o), CommentModel.class); - assertNotNull(model.getDate()); - assertNotNull(model.getAuthorName()); - assertNotNull(model.getAuthorAvatarImgUrl()); - assertNotNull(model.getContent()); - assertNotNull(model.getResponseId()); - }); - }); - } - - @Test - public void retrievePageOfLeaveMsg() throws Exception { - mockMvc.perform(get("/leaveMsg?page=1&count=10")).andDo(result -> { - JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString()); - assertEquals(SUCCESS.getCode(), object.getInt(Code)); - PageInfo pageInfo = (PageInfo) JSONObject.toBean(object.getJSONObject(Result), PageInfo.class); - assertNotEquals(0, pageInfo.getStartRow()); - assertNotEquals(0, pageInfo.getEndRow()); - assertEquals(1, pageInfo.getPageNum()); - assertEquals(10, pageInfo.getPageSize()); - pageInfo.getList().forEach(o -> { - CommentModel model = (CommentModel) JSONObject.toBean(JSONObject.fromObject(o), CommentModel.class); - assertEquals(-1, model.getArticleID()); - assertNotNull(model.getDate()); - assertNotNull(model.getAuthorName()); - assertNotNull(model.getAuthorAvatarImgUrl()); - assertNotNull(model.getContent()); - assertNotNull(model.getResponseId()); - assertFalse(model.isComment()); - }); - }); - } - - @Test - public void retrievePageAdmin() throws Exception { - mockMvc.perform(get("/admin/comment/type/1?page=1&count=10").header("Authorization", adminLogin())).andDo(result -> { - JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString()); - assertEquals(SUCCESS.getCode(), object.getInt(Code)); - PageInfo pageInfo = (PageInfo) JSONObject.toBean(object.getJSONObject(Result), PageInfo.class); - assertNotEquals(0, pageInfo.getStartRow()); - assertNotEquals(0, pageInfo.getEndRow()); - assertEquals(1, pageInfo.getPageNum()); - assertEquals(10, pageInfo.getPageSize()); - pageInfo.getList().forEach(o -> { - CommentModel model = (CommentModel) JSONObject.toBean(JSONObject.fromObject(o), CommentModel.class); - assertNotEquals(-1, model.getArticleID()); - assertNotNull(model.getDate()); - assertNotNull(model.getAuthorName()); - assertNotNull(model.getAuthorAvatarImgUrl()); - assertNotNull(model.getContent()); - assertNotNull(model.getResponseId()); - assertTrue(model.isComment()); - }); - }); - mockMvc.perform(get("/admin/comment/type/0?page=1&count=10").header("Authorization", adminLogin())).andDo(result -> { - JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString()); - assertEquals(SUCCESS.getCode(), object.getInt(Code)); - PageInfo pageInfo = (PageInfo) JSONObject.toBean(object.getJSONObject(Result), PageInfo.class); - assertNotEquals(0, pageInfo.getStartRow()); - assertNotEquals(0, pageInfo.getEndRow()); - assertEquals(1, pageInfo.getPageNum()); - assertEquals(10, pageInfo.getPageSize()); - pageInfo.getList().forEach(o -> { - CommentModel model = (CommentModel) JSONObject.toBean(JSONObject.fromObject(o), CommentModel.class); - assertEquals(-1, model.getArticleID()); - assertNotNull(model.getDate()); - assertNotNull(model.getAuthorName()); - assertNotNull(model.getAuthorAvatarImgUrl()); - assertNotNull(model.getContent()); - assertNotNull(model.getResponseId()); - assertFalse(model.isComment()); - }); - }); - } - - @Test - public void retrievePageByAuthor() throws Exception { - mockMvc.perform(get("/user/comment/type/1?page=1&count=10").header("Authorization", userLogin())).andDo(result -> { - JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString()); - assertEquals(SUCCESS.getCode(), object.getInt(Code)); - PageInfo pageInfo = (PageInfo) JSONObject.toBean(object.getJSONObject(Result), PageInfo.class); - assertNotEquals(0, pageInfo.getStartRow()); - assertNotEquals(0, pageInfo.getEndRow()); - assertEquals(1, pageInfo.getPageNum()); - assertEquals(10, pageInfo.getPageSize()); - pageInfo.getList().forEach(o -> { - CommentModel model = (CommentModel) JSONObject.toBean(JSONObject.fromObject(o), CommentModel.class); - assertNotEquals(-1, model.getArticleID()); - assertNotNull(model.getDate()); - assertNotNull(model.getAuthorName()); - assertNotNull(model.getAuthorAvatarImgUrl()); - assertNotNull(model.getContent()); - assertNotNull(model.getResponseId()); - assertTrue(model.isComment()); - }); - }); - mockMvc.perform(get("/user/comment/type/0?page=1&count=10").header("Authorization", userLogin())).andDo(result -> { - JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString()); - assertEquals(SUCCESS.getCode(), object.getInt(Code)); - PageInfo pageInfo = (PageInfo) JSONObject.toBean(object.getJSONObject(Result), PageInfo.class); - assertNotEquals(0, pageInfo.getStartRow()); - assertNotEquals(0, pageInfo.getEndRow()); - assertEquals(1, pageInfo.getPageNum()); - assertEquals(10, pageInfo.getPageSize()); - pageInfo.getList().forEach(o -> { - CommentModel model = (CommentModel) JSONObject.toBean(JSONObject.fromObject(o), CommentModel.class); - assertEquals(-1, model.getArticleID()); - assertNotNull(model.getDate()); - assertNotNull(model.getAuthorName()); - assertNotNull(model.getAuthorAvatarImgUrl()); - assertNotNull(model.getContent()); - assertNotNull(model.getResponseId()); - assertFalse(model.isComment()); - }); - }); - } } \ No newline at end of file From 03cb04ab0618f72d726ebf265054b94ab349c798 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Tue, 26 May 2020 12:54:24 +0800 Subject: [PATCH 25/33] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dbug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/cn/celess/blog/enmu/CommentStatusEnum.java | 2 -- src/main/java/cn/celess/blog/entity/ArticleTag.java | 1 - .../celess/blog/service/serviceimpl/ArticleServiceImpl.java | 3 ++- src/main/java/cn/celess/blog/util/ModalTrans.java | 2 +- src/main/resources/mapper/ArticleTagMapper.xml | 5 +++-- src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java | 2 +- .../java/cn/celess/blog/mapper/ArticleTagMapperTest.java | 2 +- src/test/java/cn/celess/blog/mapper/CategoryMapperTest.java | 4 +++- src/test/java/cn/celess/blog/mapper/TagMapperTest.java | 4 +++- 9 files changed, 14 insertions(+), 11 deletions(-) diff --git a/src/main/java/cn/celess/blog/enmu/CommentStatusEnum.java b/src/main/java/cn/celess/blog/enmu/CommentStatusEnum.java index 84ac6bc..be1ef88 100644 --- a/src/main/java/cn/celess/blog/enmu/CommentStatusEnum.java +++ b/src/main/java/cn/celess/blog/enmu/CommentStatusEnum.java @@ -1,7 +1,5 @@ package cn.celess.blog.enmu; -import com.sun.javaws.jnl.IconDesc; - /** * @Author: 小海 * @Date: 2020-05-25 08:58 diff --git a/src/main/java/cn/celess/blog/entity/ArticleTag.java b/src/main/java/cn/celess/blog/entity/ArticleTag.java index af8f5d3..6ba2184 100644 --- a/src/main/java/cn/celess/blog/entity/ArticleTag.java +++ b/src/main/java/cn/celess/blog/entity/ArticleTag.java @@ -1,6 +1,5 @@ package cn.celess.blog.entity; -import com.sun.xml.internal.ws.policy.EffectiveAlternativeSelector; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/ArticleServiceImpl.java b/src/main/java/cn/celess/blog/service/serviceimpl/ArticleServiceImpl.java index 656187b..68ae080 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/ArticleServiceImpl.java +++ b/src/main/java/cn/celess/blog/service/serviceimpl/ArticleServiceImpl.java @@ -281,7 +281,8 @@ public class ArticleServiceImpl implements ArticleService { PageData pageData = new PageData(new PageInfo
(articleList)); List articleModelList = new ArrayList<>(); articleList.forEach(article -> { - ArticleModel articleModel = ModalTrans.article(article, true); + ArticleModel articleModel = ModalTrans.article(article); + articleModel.setMdContent(null); articleModelList.add(articleModel); }); pageData.setList(articleModelList); diff --git a/src/main/java/cn/celess/blog/util/ModalTrans.java b/src/main/java/cn/celess/blog/util/ModalTrans.java index 9b58ab7..a8c817f 100644 --- a/src/main/java/cn/celess/blog/util/ModalTrans.java +++ b/src/main/java/cn/celess/blog/util/ModalTrans.java @@ -28,7 +28,7 @@ public class ModalTrans { public static ArticleModel article(Article article, boolean noMdContent) { ArticleModel article1 = article(article); - if (!noMdContent) { + if (!noMdContent || article1 == null) { return article1; } article1.setMdContent(null); diff --git a/src/main/resources/mapper/ArticleTagMapper.xml b/src/main/resources/mapper/ArticleTagMapper.xml index c1062b3..38f4ba6 100644 --- a/src/main/resources/mapper/ArticleTagMapper.xml +++ b/src/main/resources/mapper/ArticleTagMapper.xml @@ -31,7 +31,7 @@ t_id = #{tag.id}, - where at_id = #{tag.id} + where at_id = #{id} @@ -69,7 +69,8 @@ from article_tag, article, tag_category - where article_tag.a_id = article.a_id + where article_tag.at_id = #{id} + and article_tag.a_id = article.a_id and tag_category.t_id = article_tag.t_id diff --git a/src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java b/src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java index 1b7d785..163eba4 100644 --- a/src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java +++ b/src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java @@ -164,7 +164,7 @@ public class ArticleMapperTest extends BaseTest { @Test public void findAllByCategoryIdAndOpen() { - List
allByCategoryId = articleMapper.findAllByCategoryId(1); + List
allByCategoryId = articleMapper.findAllByCategoryIdAndOpen(1); assertNotEquals(0, allByCategoryId.size()); allByCategoryId.forEach(article -> assertTrue(article.getOpen())); } diff --git a/src/test/java/cn/celess/blog/mapper/ArticleTagMapperTest.java b/src/test/java/cn/celess/blog/mapper/ArticleTagMapperTest.java index fb8715d..0f2763a 100644 --- a/src/test/java/cn/celess/blog/mapper/ArticleTagMapperTest.java +++ b/src/test/java/cn/celess/blog/mapper/ArticleTagMapperTest.java @@ -106,7 +106,7 @@ public class ArticleTagMapperTest extends BaseTest { @Test public void findArticleByTagAndOpen() { ArticleTag articleTag = generateArticle(); - List articleByTag = articleTagMapper.findArticleByTag(21L); + List articleByTag = articleTagMapper.findArticleByTagAndOpen(21L); assertNotEquals(0, articleByTag.size()); articleByTag.forEach(articleTag1 -> assertEquals(articleTag.getTag().getName(), articleTag1.getTag().getName())); articleByTag.forEach(articleTag1 -> assertTrue(articleTag1.getArticle().getOpen())); diff --git a/src/test/java/cn/celess/blog/mapper/CategoryMapperTest.java b/src/test/java/cn/celess/blog/mapper/CategoryMapperTest.java index 4ab98a9..d43d79e 100644 --- a/src/test/java/cn/celess/blog/mapper/CategoryMapperTest.java +++ b/src/test/java/cn/celess/blog/mapper/CategoryMapperTest.java @@ -7,6 +7,7 @@ import org.springframework.beans.factory.annotation.Autowired; import java.util.Comparator; import java.util.List; +import java.util.stream.Collectors; import static org.junit.Assert.*; @@ -106,7 +107,8 @@ public class CategoryMapperTest extends BaseTest { @Test public void count() { List all = categoryMapper.findAll(); - assertEquals(all.size(), categoryMapper.count()); + List collect = all.stream().filter(category -> !category.isDeleted()).collect(Collectors.toList()); + assertEquals(collect.size(), categoryMapper.count()); } private Category generateCategory() { diff --git a/src/test/java/cn/celess/blog/mapper/TagMapperTest.java b/src/test/java/cn/celess/blog/mapper/TagMapperTest.java index feafcf3..b9c1445 100644 --- a/src/test/java/cn/celess/blog/mapper/TagMapperTest.java +++ b/src/test/java/cn/celess/blog/mapper/TagMapperTest.java @@ -6,6 +6,7 @@ import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; +import java.util.stream.Collectors; import static org.junit.Assert.*; @@ -79,7 +80,8 @@ public class TagMapperTest extends BaseTest { public void count() { assertNotEquals(0, tagMapper.count()); List all = tagMapper.findAll(); - assertEquals(all.size(), tagMapper.count()); + List collect = all.stream().filter(tag -> !tag.isDeleted()).collect(Collectors.toList()); + assertEquals(collect.size(), tagMapper.count()); } private Tag generateTag() { From 7aebaaa98b1244347d7ca3b987270b116f088f01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Tue, 26 May 2020 12:54:51 +0800 Subject: [PATCH 26/33] . --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index c4c8f6c..b306679 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .idea/ *.imi +*.iml target/ # 本地项目的私有文件 From 4035c7e0241b88314dd679111caed8597b7b284c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Tue, 26 May 2020 12:56:57 +0800 Subject: [PATCH 27/33] =?UTF-8?q?=E6=9B=B4=E6=94=B9sql=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- blog.iml | 149 ----------------------------- blog.sql | 270 ++++++++++++++++++++++++++++++++++------------------ newBlog.sql | 178 ---------------------------------- 3 files changed, 178 insertions(+), 419 deletions(-) delete mode 100644 blog.iml delete mode 100644 newBlog.sql diff --git a/blog.iml b/blog.iml deleted file mode 100644 index 7aecb0e..0000000 --- a/blog.iml +++ /dev/null @@ -1,149 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/blog.sql b/blog.sql index e07a364..fa4cf14 100644 --- a/blog.sql +++ b/blog.sql @@ -1,92 +1,178 @@ -CREATE DATABASE `blog`; - -USE blog; - -CREATE TABLE `article` -( - `a_id` bigint(20) primary key auto_increment, - `a_title` varchar(255) not null unique comment '文章标题', - `a_summary` varchar(255) not null comment '文章摘要', - `a_md_content` longtext not null comment '文章Markdown内容', - `a_tags_id` varchar(255) not null comment '标签id \',\'处于最尾端', - `a_category_id` bigint(20) not null comment '分类的id', - `a_url` tinytext default null comment '转载文章的原文链接', - `a_author_id` bigint(20) not null comment '作者id', - `a_is_open` boolean default true comment '文章是否可见', - `a_is_original` boolean default true comment '文章是否原创', - `next_a_id` bigint(20) default -1 comment '下篇文章id', - `pre_a_id` bigint(20) default -1 comment '前一篇文章的id', - `a_reading_number` int default 0 comment '文章阅读数', - `a_publish_date` datetime not null comment '文章发布时间', - `a_update_date` datetime default null comment '文章的更新时间' -) DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_general_ci,comment '文章表'; - -CREATE TABLE `tag` -( - `tag_id` bigint(20) primary key auto_increment, - `tag_name` varchar(255) unique not null, - `articles` tinytext default null comment 'tag对应的文章id' -) comment '标签表'; - -CREATE table `category` -( - `c_id` bigint(20) primary key auto_increment, - `c_name` varchar(255) unique not null, - `articles` varchar(255) comment '分类下的文章' -)comment '分类表'; - -CREATE TABLE `comment` -( - `co_id` bigint(20) primary key auto_increment, - `co_article_id` bigint(20) default -1 comment '文章id', - `is_comment` boolean default true comment '是否是评论', - `author_id` bigint(20) not null comment '留言者id', - `co_content` text not null comment '评论/留言内容', - `co_date` datetime not null comment '评论/留言的日期', - `co_pid` bigint not null default -1 comment '评论/留言的父id', - `co_response_id` tinytext -) DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_general_ci,comment '评论/留言表'; - -CREATE TABLE `links` -( - `site_id` bigint(20) primary key auto_increment, - `site_name` varchar(255) not null comment '友站名称', - `is_open` boolean default true comment '是否公开', - `site_url` varchar(255) not null comment '首页地址' -) comment '友站表'; - -CREATE TABLE `visitor` -( - `v_id` bigint(20) primary key auto_increment, - `v_date` datetime not null comment '访问时间', - `v_ip` varchar(255) not null comment '访客ip', - `v_user_agent` text comment '访客ua' -) comment '访客表'; - - - -CREATE TABLE IF NOT EXISTS `web_update` -( - `update_id` bigint(20) primary key auto_increment, - `update_info` varchar(255) not null comment '更新内容', - `update_time` datetime not null comment '更新时间' -) comment '更新内容表'; - -create table `user` -( - `u_id` int not null primary key auto_increment, - `u_email` varchar(50) not null, - `u_uid` varchar(40) default null comment '用户唯一标识码', - `u_pwd` varchar(40) not null comment '密码', - `email_status` boolean default false comment '邮箱验证状态', - `u_avatar` varchar(255) comment '用户头像', - `u_desc` tinytext comment '用户的描述', - `recently_landed_time` datetime comment '最近的登录时间', - `email_verify_id` varchar(40) comment '用于找回密码或验证邮箱的id', - `display_name` varchar(30) comment '展示的昵称', - `role` varchar(40) not null default 'user' comment '权限组', - unique key `uni_user_id` (`u_id`), - unique key `uni_user_uid` (`u_uid`), - unique key `uni_user_email` (`u_email`) -) comment '用户表'; - +CREATE DATABASE `t_blog`; + +USE t_blog; + +CREATE TABLE `article` +( + `a_id` bigint(20) primary key auto_increment, + `a_title` varchar(255) not null unique comment '文章标题', + `a_summary` varchar(255) not null comment '文章摘要', + `a_md_content` longtext not null comment '文章Markdown内容', + `a_url` tinytext default null comment '转载文章的原文链接', + `a_author_id` int not null comment '作者id', + `a_is_original` boolean default true comment '文章是否原创', + `a_reading_number` int default 0 comment '文章阅读数', + `a_like` int default 0 comment '文章点赞数', + `a_dislike` int default 0 comment '文章不喜欢数', + `a_category_id` int not null comment '文章分类id', + `a_publish_date` datetime default CURRENT_TIMESTAMP comment '文章发布时间', + `a_update_date` datetime default null comment '文章的更新时间', + `a_is_open` boolean default true comment '文章是否可见', + `is_delete` boolean not null default false comment '该数据是否被删除' +) DEFAULT CHARSET = utf8mb4 + COLLATE utf8mb4_general_ci,comment '文章表'; + +CREATE TABLE `article_tag` +( + `at_id` bigint(20) primary key auto_increment, + `a_id` bigint(20) not null comment '文章id', + `t_id` bigint not null comment 'tag/category 的id', + `is_delete` boolean not null default false comment '该数据是否被删除' +) comment '文章标签表'; + +CREATE TABLE `tag_category` +( + `t_id` bigint(20) primary key auto_increment, + `t_name` varchar(255) not null, + `is_category` boolean not null default true, +) comment '标签和分类表'; + +CREATE TABLE `comment` +( + `co_id` bigint(20) primary key auto_increment, + `co_page_path` varchar(255) not null comment '评论/留言的页面', + `co_content` text not null comment '评论/留言内容', + `co_date` datetime not null comment '评论/留言的日期', + `co_status` tinyint not null default 0 comment '评论的状态', + `co_pid` bigint not null default -1 comment '评论/留言的父id', + `co_from_author_id` int not null comment '留言者id', + `co_to_author_id` int default null comment '父评论的作者id', + `is_delete` boolean not null default false comment '该数据是否被删除' +) DEFAULT CHARSET = utf8mb4 + COLLATE utf8mb4_general_ci,comment '评论/留言表'; + + + +CREATE TABLE `links` +( + `l_id` bigint(20) primary key auto_increment, + `l_name` varchar(255) not null comment '友站名称', + `l_is_open` boolean default true comment '是否公开', + `l_url` varchar(255) not null comment '首页地址', + `l_icon_path` varchar(255) not null comment '友链的icon地址', + `l_desc` varchar(255) not null comment '友链的说明描述', + `is_delete` boolean not null default false comment '该数据是否被删除' +) comment '友站表'; + +CREATE TABLE `visitor` +( + `v_id` bigint(20) primary key auto_increment, + `v_date` datetime not null comment '访问时间', + `v_ip` varchar(255) not null comment '访客ip', + `v_user_agent` text comment '访客ua', + `is_delete` boolean not null default false comment '该数据是否被删除' +) comment '访客表'; + +CREATE TABLE `web_update` +( + `wu_id` int primary key auto_increment, + `wu_info` varchar(255) not null comment '更新内容', + `wu_time` datetime not null comment '更新时间', + `is_delete` boolean not null default false comment '该数据是否被删除' +) comment '更新内容表'; + +CREATE TABLE `user` +( + `u_id` int not null primary key auto_increment, + `u_email` varchar(50) not null, + `u_pwd` varchar(40) not null comment '密码', + `u_email_status` boolean default false comment '邮箱验证状态', + `u_avatar` varchar(255) default null comment '用户头像', + `u_desc` tinytext default null comment '用户的描述', + `u_recently_landed_time` datetime default null comment '最近的登录时间', + `u_display_name` varchar(30) default null comment '展示的昵称', + `u_role` varchar(40) not null default 'user' comment '权限组', + `status` tinyint(1) not null default 0 comment '账户状态', + unique key `uni_user_id` (`u_id`), + unique key `uni_user_email` (`u_email`) +) comment '用户表'; + + +CREATE VIEW articleView + (articleId, title, summary, mdContent, url, isOriginal, readingCount, likeCount, dislikeCount, + publishDate, updateDate, isOpen, + categoryId, categoryName, tagId, tagName, + authorId, userEmail, userAvatar, userDisplayName, isDelete) +as +select article.a_id as articleId, + article.a_title as title, + article.a_summary as summary, + article.a_md_content as mdContent, + article.a_url as url, + article.a_is_original as isOriginal, + article.a_reading_number as readingCount, + article.a_like as likeCount, + article.a_dislike as dislikeCount, + article.a_publish_date as publishDate, + article.a_update_date as updateDate, + article.a_is_open as isOpen, + category.t_id as categoryId, + category.t_name as categoryName, + tag.t_id as tagId, + tag.t_name as tagName, + user.u_id as authorId, + user.u_email as userEmail, + user.u_avatar as userAvatar, + user.u_display_name as userDisplayName, + article.is_delete as isDelete +from article, + tag_category as tag, + tag_category as category, + article_tag, + user +where article.a_id = article_tag.a_id + and article_tag.t_id = tag.t_id + and tag.is_category = false + and article.a_category_id = category.t_id + and category.is_category = true + and article.a_author_id = user.u_id; + + +CREATE VIEW commentView + (commentId, pagePath, content, date, status, pid, toAuthorId, toAuthorEmail, toAuthorDisplayName, + toAuthorAvatar, fromAuthorId, fromAuthorEmail, fromAuthorDisplayName, + fromAuthorAvatar, isDelete) +as +select cuT.co_id as commentId, + cuT.co_page_path as pagePath, + cuT.co_content as content, + cuT.co_date as date, + cuT.co_status as status, + cuT.co_pid as pid, + cuT.co_to_author_id as toAuthorId, + cuT.toEmail as toAuthorEmail, + cuT.toDisplayName as toAuthorDisplayName, + cuT.toAvatar as toAuthorAvatar, + userFrom.u_id as fromAuthorId, + userFrom.u_email as fromAuthorEmail, + userFrom.u_display_name as fromAuthorDisplayName, + userFrom.u_avatar as fromAuthorAvatar, + cuT.is_delete as isDelete +from (select comment.co_id, + comment.co_page_path, + comment.co_content, + comment.co_date, + comment.co_status, + comment.co_pid, + comment.co_from_author_id, + comment.co_to_author_id, + userTo.u_email as toEmail, + userTo.u_display_name as toDisplayName, + userTo.u_avatar as toAvatar, + comment.is_delete + from comment + left join user userTo on (comment.co_to_author_id = userTo.u_id) + ) as cuT, + user as userFrom +where cuT.co_from_author_id = userFrom.u_id; + diff --git a/newBlog.sql b/newBlog.sql deleted file mode 100644 index fa4cf14..0000000 --- a/newBlog.sql +++ /dev/null @@ -1,178 +0,0 @@ -CREATE DATABASE `t_blog`; - -USE t_blog; - -CREATE TABLE `article` -( - `a_id` bigint(20) primary key auto_increment, - `a_title` varchar(255) not null unique comment '文章标题', - `a_summary` varchar(255) not null comment '文章摘要', - `a_md_content` longtext not null comment '文章Markdown内容', - `a_url` tinytext default null comment '转载文章的原文链接', - `a_author_id` int not null comment '作者id', - `a_is_original` boolean default true comment '文章是否原创', - `a_reading_number` int default 0 comment '文章阅读数', - `a_like` int default 0 comment '文章点赞数', - `a_dislike` int default 0 comment '文章不喜欢数', - `a_category_id` int not null comment '文章分类id', - `a_publish_date` datetime default CURRENT_TIMESTAMP comment '文章发布时间', - `a_update_date` datetime default null comment '文章的更新时间', - `a_is_open` boolean default true comment '文章是否可见', - `is_delete` boolean not null default false comment '该数据是否被删除' -) DEFAULT CHARSET = utf8mb4 - COLLATE utf8mb4_general_ci,comment '文章表'; - -CREATE TABLE `article_tag` -( - `at_id` bigint(20) primary key auto_increment, - `a_id` bigint(20) not null comment '文章id', - `t_id` bigint not null comment 'tag/category 的id', - `is_delete` boolean not null default false comment '该数据是否被删除' -) comment '文章标签表'; - -CREATE TABLE `tag_category` -( - `t_id` bigint(20) primary key auto_increment, - `t_name` varchar(255) not null, - `is_category` boolean not null default true, -) comment '标签和分类表'; - -CREATE TABLE `comment` -( - `co_id` bigint(20) primary key auto_increment, - `co_page_path` varchar(255) not null comment '评论/留言的页面', - `co_content` text not null comment '评论/留言内容', - `co_date` datetime not null comment '评论/留言的日期', - `co_status` tinyint not null default 0 comment '评论的状态', - `co_pid` bigint not null default -1 comment '评论/留言的父id', - `co_from_author_id` int not null comment '留言者id', - `co_to_author_id` int default null comment '父评论的作者id', - `is_delete` boolean not null default false comment '该数据是否被删除' -) DEFAULT CHARSET = utf8mb4 - COLLATE utf8mb4_general_ci,comment '评论/留言表'; - - - -CREATE TABLE `links` -( - `l_id` bigint(20) primary key auto_increment, - `l_name` varchar(255) not null comment '友站名称', - `l_is_open` boolean default true comment '是否公开', - `l_url` varchar(255) not null comment '首页地址', - `l_icon_path` varchar(255) not null comment '友链的icon地址', - `l_desc` varchar(255) not null comment '友链的说明描述', - `is_delete` boolean not null default false comment '该数据是否被删除' -) comment '友站表'; - -CREATE TABLE `visitor` -( - `v_id` bigint(20) primary key auto_increment, - `v_date` datetime not null comment '访问时间', - `v_ip` varchar(255) not null comment '访客ip', - `v_user_agent` text comment '访客ua', - `is_delete` boolean not null default false comment '该数据是否被删除' -) comment '访客表'; - -CREATE TABLE `web_update` -( - `wu_id` int primary key auto_increment, - `wu_info` varchar(255) not null comment '更新内容', - `wu_time` datetime not null comment '更新时间', - `is_delete` boolean not null default false comment '该数据是否被删除' -) comment '更新内容表'; - -CREATE TABLE `user` -( - `u_id` int not null primary key auto_increment, - `u_email` varchar(50) not null, - `u_pwd` varchar(40) not null comment '密码', - `u_email_status` boolean default false comment '邮箱验证状态', - `u_avatar` varchar(255) default null comment '用户头像', - `u_desc` tinytext default null comment '用户的描述', - `u_recently_landed_time` datetime default null comment '最近的登录时间', - `u_display_name` varchar(30) default null comment '展示的昵称', - `u_role` varchar(40) not null default 'user' comment '权限组', - `status` tinyint(1) not null default 0 comment '账户状态', - unique key `uni_user_id` (`u_id`), - unique key `uni_user_email` (`u_email`) -) comment '用户表'; - - -CREATE VIEW articleView - (articleId, title, summary, mdContent, url, isOriginal, readingCount, likeCount, dislikeCount, - publishDate, updateDate, isOpen, - categoryId, categoryName, tagId, tagName, - authorId, userEmail, userAvatar, userDisplayName, isDelete) -as -select article.a_id as articleId, - article.a_title as title, - article.a_summary as summary, - article.a_md_content as mdContent, - article.a_url as url, - article.a_is_original as isOriginal, - article.a_reading_number as readingCount, - article.a_like as likeCount, - article.a_dislike as dislikeCount, - article.a_publish_date as publishDate, - article.a_update_date as updateDate, - article.a_is_open as isOpen, - category.t_id as categoryId, - category.t_name as categoryName, - tag.t_id as tagId, - tag.t_name as tagName, - user.u_id as authorId, - user.u_email as userEmail, - user.u_avatar as userAvatar, - user.u_display_name as userDisplayName, - article.is_delete as isDelete -from article, - tag_category as tag, - tag_category as category, - article_tag, - user -where article.a_id = article_tag.a_id - and article_tag.t_id = tag.t_id - and tag.is_category = false - and article.a_category_id = category.t_id - and category.is_category = true - and article.a_author_id = user.u_id; - - -CREATE VIEW commentView - (commentId, pagePath, content, date, status, pid, toAuthorId, toAuthorEmail, toAuthorDisplayName, - toAuthorAvatar, fromAuthorId, fromAuthorEmail, fromAuthorDisplayName, - fromAuthorAvatar, isDelete) -as -select cuT.co_id as commentId, - cuT.co_page_path as pagePath, - cuT.co_content as content, - cuT.co_date as date, - cuT.co_status as status, - cuT.co_pid as pid, - cuT.co_to_author_id as toAuthorId, - cuT.toEmail as toAuthorEmail, - cuT.toDisplayName as toAuthorDisplayName, - cuT.toAvatar as toAuthorAvatar, - userFrom.u_id as fromAuthorId, - userFrom.u_email as fromAuthorEmail, - userFrom.u_display_name as fromAuthorDisplayName, - userFrom.u_avatar as fromAuthorAvatar, - cuT.is_delete as isDelete -from (select comment.co_id, - comment.co_page_path, - comment.co_content, - comment.co_date, - comment.co_status, - comment.co_pid, - comment.co_from_author_id, - comment.co_to_author_id, - userTo.u_email as toEmail, - userTo.u_display_name as toDisplayName, - userTo.u_avatar as toAvatar, - comment.is_delete - from comment - left join user userTo on (comment.co_to_author_id = userTo.u_id) - ) as cuT, - user as userFrom -where cuT.co_from_author_id = userFrom.u_id; - From 450978ecd93c310ed83ee62ffb378f4b7f3e6d6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Tue, 26 May 2020 13:59:36 +0800 Subject: [PATCH 28/33] =?UTF-8?q?=E4=BF=AE=E6=94=B9Response=20=E7=9A=84dat?= =?UTF-8?q?e=E5=93=8D=E5=BA=94=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../filter/AuthenticationFilter.java | 19 +++--- .../filter/MultipleSubmitFilter.java | 2 +- .../blog/controller/ArticleController.java | 23 ++++---- .../blog/controller/CategoryController.java | 9 ++- .../blog/controller/CommentController.java | 15 +++-- .../blog/controller/LinksController.java | 17 +++--- .../java/cn/celess/blog/controller/Other.java | 16 ++--- .../celess/blog/controller/TagController.java | 12 ++-- .../blog/controller/UserController.java | 39 ++++++------ .../blog/controller/VisitorController.java | 13 ++-- .../controller/WebUpdateInfoController.java | 14 ++--- .../blog/exception/ExceptionHandle.java | 17 +++--- .../service/serviceimpl/UserServiceImpl.java | 3 +- .../cn/celess/blog/util/ResponseUtil.java | 59 ------------------- 14 files changed, 92 insertions(+), 166 deletions(-) delete mode 100644 src/main/java/cn/celess/blog/util/ResponseUtil.java diff --git a/src/main/java/cn/celess/blog/configuration/filter/AuthenticationFilter.java b/src/main/java/cn/celess/blog/configuration/filter/AuthenticationFilter.java index 3734b13..b26597a 100644 --- a/src/main/java/cn/celess/blog/configuration/filter/AuthenticationFilter.java +++ b/src/main/java/cn/celess/blog/configuration/filter/AuthenticationFilter.java @@ -1,16 +1,15 @@ package cn.celess.blog.configuration.filter; import cn.celess.blog.enmu.ResponseEnum; +import cn.celess.blog.entity.Response; import cn.celess.blog.service.UserService; import cn.celess.blog.util.JwtUtil; import cn.celess.blog.util.RedisUtil; -import cn.celess.blog.util.ResponseUtil; import net.sf.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.HandlerInterceptor; -import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -22,6 +21,11 @@ import java.io.IOException; * @Description: 鉴权拦截器 */ public class AuthenticationFilter implements HandlerInterceptor { + private static final Logger logger = LoggerFactory.getLogger(AuthenticationFilter.class); + private static final String USER_PREFIX = "/user"; + private static final String ADMIN_PREFIX = "/admin"; + private static final String ROLE_ADMIN = "admin"; + private static final String ROLE_USER = "user"; @Autowired JwtUtil jwtUtil; @Autowired @@ -29,13 +33,6 @@ public class AuthenticationFilter implements HandlerInterceptor { @Autowired UserService userService; - private static final Logger logger = LoggerFactory.getLogger(AuthenticationFilter.class); - - private static final String USER_PREFIX = "/user"; - private static final String ADMIN_PREFIX = "/admin"; - private static final String ROLE_ADMIN = "admin"; - private static final String ROLE_USER = "user"; - @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String path = request.getRequestURI(); @@ -67,7 +64,7 @@ public class AuthenticationFilter implements HandlerInterceptor { if (role.equals(ROLE_USER) || role.equals(ROLE_ADMIN)) { // 更新token String token = jwtUtil.updateTokenDate(jwtStr); - response.setHeader("Authorization",token); + response.setHeader("Authorization", token); } if (role.equals(ROLE_ADMIN)) { // admin @@ -84,7 +81,7 @@ public class AuthenticationFilter implements HandlerInterceptor { response.setHeader("Content-Type", "application/json;charset=UTF-8"); try { logger.info("鉴权失败,[code:{},msg:{},path:{}]", e.getCode(), e.getMsg(), request.getRequestURI() + "?" + request.getQueryString()); - response.getWriter().println(JSONObject.fromObject(ResponseUtil.response(e, null))); + response.getWriter().println(JSONObject.fromObject(Response.response(e, null))); } catch (IOException ex) { ex.printStackTrace(); } diff --git a/src/main/java/cn/celess/blog/configuration/filter/MultipleSubmitFilter.java b/src/main/java/cn/celess/blog/configuration/filter/MultipleSubmitFilter.java index c0557cc..c0d908d 100644 --- a/src/main/java/cn/celess/blog/configuration/filter/MultipleSubmitFilter.java +++ b/src/main/java/cn/celess/blog/configuration/filter/MultipleSubmitFilter.java @@ -28,7 +28,7 @@ public class MultipleSubmitFilter implements HandlerInterceptor { // 请求参数和路径均相同 且请求时间间隔小于 WAIT_TIME response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); - Response result = new Response(ResponseEnum.FAILURE.getCode(), "重复请求", null, System.currentTimeMillis()); + Response result = new Response(ResponseEnum.FAILURE.getCode(), "重复请求", null); response.getWriter().println(result.toString()); return false; } diff --git a/src/main/java/cn/celess/blog/controller/ArticleController.java b/src/main/java/cn/celess/blog/controller/ArticleController.java index 1faf686..c4b011f 100644 --- a/src/main/java/cn/celess/blog/controller/ArticleController.java +++ b/src/main/java/cn/celess/blog/controller/ArticleController.java @@ -6,7 +6,6 @@ import cn.celess.blog.entity.model.ArticleModel; import cn.celess.blog.entity.request.ArticleReq; import cn.celess.blog.service.ArticleService; import cn.celess.blog.util.RedisUserUtil; -import cn.celess.blog.util.ResponseUtil; import cn.celess.blog.util.SitemapGenerateUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -36,7 +35,7 @@ public class ArticleController { public Response create(@RequestBody ArticleReq body) { ArticleModel articleModel = articleService.create(body); sitemapGenerateUtil.createSitemap(); - return ResponseUtil.success(articleModel); + return Response.success(articleModel); } /** @@ -49,7 +48,7 @@ public class ArticleController { public Response delete(@RequestParam("articleID") long articleId) { boolean delete = articleService.delete(articleId); sitemapGenerateUtil.createSitemap(); - return ResponseUtil.success(delete); + return Response.success(delete); } /** @@ -62,7 +61,7 @@ public class ArticleController { public Response update(@RequestBody ArticleReq body) { ArticleModel update = articleService.update(body); sitemapGenerateUtil.createSitemap(); - return ResponseUtil.success(update); + return Response.success(update); } /** @@ -82,11 +81,11 @@ public class ArticleController { HttpServletRequest request) { ArticleModel article = articleService.retrieveOneById(articleId, is4update); if (article.getOpen()) { - return ResponseUtil.success(article); + return Response.success(article); } else if (article.getAuthor().getId().equals(redisUserUtil.get().getId())) { - return ResponseUtil.success(article); + return Response.success(article); } - return ResponseUtil.response(ResponseEnum.PERMISSION_ERROR, null); + return Response.response(ResponseEnum.PERMISSION_ERROR, null); } /** @@ -99,7 +98,7 @@ public class ArticleController { @GetMapping("/articles") public Response articles(@RequestParam(name = "page", defaultValue = "1") int page, @RequestParam(name = "count", defaultValue = "5") int count) { - return ResponseUtil.success(articleService.retrievePageForOpen(count, page)); + return Response.success(articleService.retrievePageForOpen(count, page)); } /** @@ -112,7 +111,7 @@ public class ArticleController { @GetMapping("/admin/articles") public Response adminArticles(@RequestParam(name = "page", defaultValue = "1") int page, @RequestParam(name = "count", defaultValue = "10") int count) { - return ResponseUtil.success(articleService.adminArticles(count, page)); + return Response.success(articleService.adminArticles(count, page)); } /** @@ -127,7 +126,7 @@ public class ArticleController { public Response findByCategory(@PathVariable("name") String name, @RequestParam(name = "page", defaultValue = "1") int page, @RequestParam(name = "count", defaultValue = "10") int count) { - return ResponseUtil.success(articleService.findByCategory(name, page, count)); + return Response.success(articleService.findByCategory(name, page, count)); } /** @@ -142,13 +141,13 @@ public class ArticleController { public Response findByTag(@PathVariable("name") String name, @RequestParam(name = "page", defaultValue = "1") int page, @RequestParam(name = "count", defaultValue = "10") int count) { - return ResponseUtil.success(articleService.findByTag(name, page, count)); + return Response.success(articleService.findByTag(name, page, count)); } @GetMapping("/createSitemap") public Response createSitemap() { sitemapGenerateUtil.createSitemap(); - return ResponseUtil.success(null); + return Response.success(null); } } diff --git a/src/main/java/cn/celess/blog/controller/CategoryController.java b/src/main/java/cn/celess/blog/controller/CategoryController.java index 59617ff..08f2791 100644 --- a/src/main/java/cn/celess/blog/controller/CategoryController.java +++ b/src/main/java/cn/celess/blog/controller/CategoryController.java @@ -2,7 +2,6 @@ package cn.celess.blog.controller; import cn.celess.blog.entity.Response; import cn.celess.blog.service.CategoryService; -import cn.celess.blog.util.ResponseUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -24,7 +23,7 @@ public class CategoryController { */ @PostMapping("/admin/category/create") public Response addOne(@RequestParam("name") String name) { - return ResponseUtil.success(categoryService.create(name)); + return Response.success(categoryService.create(name)); } /** @@ -35,7 +34,7 @@ public class CategoryController { */ @DeleteMapping("/admin/category/del") public Response deleteOne(@RequestParam("id") long id) { - return ResponseUtil.success(categoryService.delete(id)); + return Response.success(categoryService.delete(id)); } /** @@ -48,7 +47,7 @@ public class CategoryController { @PutMapping("/admin/category/update") public Response updateOne(@RequestParam("id") Long id, @RequestParam("name") String name) { - return ResponseUtil.success(categoryService.update(id, name)); + return Response.success(categoryService.update(id, name)); } /** @@ -59,6 +58,6 @@ public class CategoryController { @GetMapping("/categories") public Response getPage(@RequestParam(name = "page", defaultValue = "1") int page, @RequestParam(name = "count", defaultValue = "1000") int count) { - return ResponseUtil.success(categoryService.retrievePage(page, count)); + return Response.success(categoryService.retrievePage(page, count)); } } diff --git a/src/main/java/cn/celess/blog/controller/CommentController.java b/src/main/java/cn/celess/blog/controller/CommentController.java index 8234490..fb87a07 100644 --- a/src/main/java/cn/celess/blog/controller/CommentController.java +++ b/src/main/java/cn/celess/blog/controller/CommentController.java @@ -1,10 +1,8 @@ package cn.celess.blog.controller; -import cn.celess.blog.entity.Comment; import cn.celess.blog.entity.Response; import cn.celess.blog.entity.request.CommentReq; import cn.celess.blog.service.CommentService; -import cn.celess.blog.util.ResponseUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -26,17 +24,17 @@ public class CommentController { */ @PostMapping("/user/comment/create") public Response addOne(@RequestBody CommentReq reqBody) { - return ResponseUtil.success(commentService.create(reqBody)); + return Response.success(commentService.create(reqBody)); } @DeleteMapping("/user/comment/del") public Response delete(@RequestParam("id") long id) { - return ResponseUtil.success(commentService.delete(id)); + return Response.success(commentService.delete(id)); } @PutMapping("/user/comment/update") public Response update(@RequestBody CommentReq reqBody) { - return ResponseUtil.success(commentService.update(reqBody)); + return Response.success(commentService.update(reqBody)); } /** @@ -52,7 +50,7 @@ public class CommentController { @RequestParam(value = "pid", required = false, defaultValue = "-1") long pid, @RequestParam(value = "count", required = false, defaultValue = "10") int count, @RequestParam(value = "page", required = false, defaultValue = "1") int page) { - return ResponseUtil.success(commentService.retrievePageByPageAndPid(pagePath, pid, page, count)); + return Response.success(commentService.retrievePageByPageAndPid(pagePath, pid, page, count)); } /** @@ -63,17 +61,18 @@ public class CommentController { * @param page page * @return Response */ + // FIXME:: 左斜线转义的异常 @GetMapping("/comment/pagePath/{pagePath}") public Response retrievePage(@PathVariable("pagePath") String pagePath, @RequestParam(value = "count", required = false, defaultValue = "10") int count, @RequestParam(value = "page", required = false, defaultValue = "1") int page) { - return ResponseUtil.success(commentService.retrievePage(pagePath, page, count)); + return Response.success(commentService.retrievePage(pagePath, page, count)); } @GetMapping("/user/comment/pagePath/{pagePath}") public Response userComment(@PathVariable("pagePath") String pagePath, @RequestParam(value = "count", required = false, defaultValue = "10") int count, @RequestParam(value = "page", required = false, defaultValue = "1") int page) { - return ResponseUtil.success(commentService.retrievePageByAuthor(pagePath, page, count)); + return Response.success(commentService.retrievePageByAuthor(pagePath, page, count)); } } diff --git a/src/main/java/cn/celess/blog/controller/LinksController.java b/src/main/java/cn/celess/blog/controller/LinksController.java index e81ee0e..bbe8115 100644 --- a/src/main/java/cn/celess/blog/controller/LinksController.java +++ b/src/main/java/cn/celess/blog/controller/LinksController.java @@ -9,7 +9,6 @@ import cn.celess.blog.service.MailService; import cn.celess.blog.service.PartnerSiteService; import cn.celess.blog.util.RedisUtil; import cn.celess.blog.util.RegexUtil; -import cn.celess.blog.util.ResponseUtil; import cn.celess.blog.util.DateFormatUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; @@ -37,17 +36,17 @@ public class LinksController { @PostMapping("/admin/links/create") public Response create(@RequestBody LinkReq reqBody) { - return ResponseUtil.success(partnerSiteService.create(reqBody)); + return Response.success(partnerSiteService.create(reqBody)); } @DeleteMapping("/admin/links/del/{id}") public Response del(@PathVariable("id") long id) { - return ResponseUtil.success(partnerSiteService.del(id)); + return Response.success(partnerSiteService.del(id)); } @PutMapping("/admin/links/update") public Response update(@RequestBody LinkReq reqBody) { - return ResponseUtil.success(partnerSiteService.update(reqBody)); + return Response.success(partnerSiteService.update(reqBody)); } @GetMapping("/links") @@ -60,13 +59,13 @@ public class LinksController { sites.add(p); } } - return ResponseUtil.success(sites); + return Response.success(sites); } @GetMapping("/admin/links") public Response all(@RequestParam("page") int page, @RequestParam("count") int count) { - return ResponseUtil.success(partnerSiteService.partnerSitePages(page, count)); + return Response.success(partnerSiteService.partnerSitePages(page, count)); } @PostMapping("/apply") @@ -74,10 +73,10 @@ public class LinksController { @RequestParam("url") String url) { // TODO :: 弃用发送邮件的方式。 if (name == null || name.replaceAll(" ", "").isEmpty()) { - return ResponseUtil.response(ResponseEnum.PARAMETERS_ERROR, null); + return Response.response(ResponseEnum.PARAMETERS_ERROR, null); } if (!RegexUtil.urlMatch(url)) { - return ResponseUtil.response(ResponseEnum.PARAMETERS_URL_ERROR, null); + return Response.response(ResponseEnum.PARAMETERS_URL_ERROR, null); } String applyTimeStr = redisUtil.get(request.getRemoteAddr() + "-Apply"); int applyTime = 0; @@ -93,6 +92,6 @@ public class LinksController { message.setText("name:" + name + "\nurl:" + url + "\n" + DateFormatUtil.getNow()); Boolean send = mailService.send(message); redisUtil.setEx(request.getRemoteAddr() + "-Apply", applyTime + 1 + "", 2, TimeUnit.HOURS); - return send ? ResponseUtil.success("") : ResponseUtil.failure(""); + return send ? Response.success("") : Response.failure(""); } } diff --git a/src/main/java/cn/celess/blog/controller/Other.java b/src/main/java/cn/celess/blog/controller/Other.java index 8f18ea5..d9e0d99 100644 --- a/src/main/java/cn/celess/blog/controller/Other.java +++ b/src/main/java/cn/celess/blog/controller/Other.java @@ -8,7 +8,6 @@ import cn.celess.blog.service.CountService; import cn.celess.blog.service.QiniuService; import cn.celess.blog.util.HttpUtil; import cn.celess.blog.util.RedisUtil; -import cn.celess.blog.util.ResponseUtil; import cn.celess.blog.util.VeriCodeUtil; import net.sf.json.JSONArray; import net.sf.json.JSONObject; @@ -24,9 +23,6 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.*; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.charset.StandardCharsets; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; @@ -58,7 +54,7 @@ public class Other { countMap.put("categoryCount", countService.getCategoriesCount()); countMap.put("tagCount", countService.getTagsCount()); countMap.put("visitorCount", countService.getVisitorCount()); - return ResponseUtil.success(countMap); + return Response.success(countMap); } @@ -79,7 +75,7 @@ public class Other { } map.put("sessionID", request.getSession().getId()); map.put("request.getRemoteAddr()", request.getRemoteAddr()); - return ResponseUtil.success(map); + return Response.success(map); } /** @@ -122,10 +118,10 @@ public class Other { if (code.equals(codeStr)) { request.getSession().removeAttribute("code"); request.getSession().setAttribute("verImgCodeStatus", true); - return ResponseUtil.success("验证成功"); + return Response.success("验证成功"); } else { request.getSession().removeAttribute("code"); - return ResponseUtil.failure("验证失败,请重新获取验证码"); + return Response.failure("验证失败,请重新获取验证码"); } } @@ -181,10 +177,10 @@ public class Other { try { imageObj = JSONObject.fromObject(HttpUtil.get("https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN")); } catch (IOException e) { - return ResponseUtil.failure(null); + return Response.failure(null); } JSONArray jsonArray = imageObj.getJSONArray("images"); String imageName = jsonArray.getJSONObject(0).getString("url"); - return ResponseUtil.success("https://cn.bing.com" + imageName); + return Response.success("https://cn.bing.com" + imageName); } } diff --git a/src/main/java/cn/celess/blog/controller/TagController.java b/src/main/java/cn/celess/blog/controller/TagController.java index c95ed1b..95abe06 100644 --- a/src/main/java/cn/celess/blog/controller/TagController.java +++ b/src/main/java/cn/celess/blog/controller/TagController.java @@ -1,10 +1,8 @@ package cn.celess.blog.controller; import cn.celess.blog.entity.Response; -import cn.celess.blog.entity.Tag; import cn.celess.blog.entity.model.TagModel; import cn.celess.blog.service.TagService; -import cn.celess.blog.util.ResponseUtil; import net.sf.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -24,24 +22,24 @@ public class TagController { @PostMapping("/admin/tag/create") public Response addOne(@RequestParam("name") String name) { - return ResponseUtil.success(tagService.create(name)); + return Response.success(tagService.create(name)); } @DeleteMapping("/admin/tag/del") public Response delOne(@RequestParam("id") long id) { - return ResponseUtil.success(tagService.delete(id)); + return Response.success(tagService.delete(id)); } @PutMapping("/admin/tag/update") public Response updateOne(@RequestParam("id") Long id, @RequestParam("name") String name) { - return ResponseUtil.success(tagService.update(id, name)); + return Response.success(tagService.update(id, name)); } @GetMapping("/tags") public Response getPage(@RequestParam(required = false, defaultValue = "10", value = "count") int count, @RequestParam(required = false, defaultValue = "1", value = "page") int page) { - return ResponseUtil.success(tagService.retrievePage(page, count)); + return Response.success(tagService.retrievePage(page, count)); } @GetMapping("/tags/nac") @@ -54,7 +52,7 @@ public class TagController { jsonObject.put("size", t.getArticles().size()); nameAndCount.add(jsonObject); } - return ResponseUtil.success(nameAndCount); + return Response.success(nameAndCount); } } diff --git a/src/main/java/cn/celess/blog/controller/UserController.java b/src/main/java/cn/celess/blog/controller/UserController.java index 8a31601..7b7f9f1 100644 --- a/src/main/java/cn/celess/blog/controller/UserController.java +++ b/src/main/java/cn/celess/blog/controller/UserController.java @@ -4,7 +4,6 @@ import cn.celess.blog.entity.Response; import cn.celess.blog.entity.request.LoginReq; import cn.celess.blog.entity.request.UserReq; import cn.celess.blog.service.UserService; -import cn.celess.blog.util.ResponseUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @@ -23,28 +22,28 @@ public class UserController { @PostMapping("/login") public Response login(@RequestBody LoginReq loginReq) { - return ResponseUtil.success(userService.login(loginReq)); + return Response.success(userService.login(loginReq)); } @PostMapping("/registration") public Response registration(@RequestParam("email") String email, @RequestParam("password") String password) { - return ResponseUtil.success(userService.registration(email, password)); + return Response.success(userService.registration(email, password)); } @GetMapping("/logout") public Response logout() { - return ResponseUtil.success(userService.logout()); + return Response.success(userService.logout()); } @PutMapping("/user/userInfo/update") public Response updateInfo(String desc, String displayName) { - return ResponseUtil.success(userService.update(desc, displayName)); + return Response.success(userService.update(desc, displayName)); } @GetMapping("/user/userInfo") public Response getUserInfo() { - return ResponseUtil.success(userService.getUserInfoBySession()); + return Response.success(userService.getUserInfoBySession()); } /** @@ -58,7 +57,7 @@ public class UserController { @ResponseBody public Response upload(@RequestParam("file") MultipartFile file) throws IOException { if (file.isEmpty()) { - return ResponseUtil.failure("上传失败,请选择文件"); + return Response.failure("上传失败,请选择文件"); } String fileName = file.getOriginalFilename(); String mime = fileName.substring(fileName.lastIndexOf(".")); @@ -66,64 +65,64 @@ public class UserController { ".jpeg".equals(mime.toLowerCase()) || ".bmp".equals(mime.toLowerCase())) { return (Response) userService.updateUserAavatarImg(file.getInputStream(), mime); } - return ResponseUtil.failure("请上传图片文件"); + return Response.failure("请上传图片文件"); } @PostMapping("/sendResetPwdEmail") public Response sendResetPwdEmail(@RequestParam("email") String email) { - return ResponseUtil.success(userService.sendResetPwdEmail(email)); + return Response.success(userService.sendResetPwdEmail(email)); } @PostMapping("/sendVerifyEmail") public Response sendVerifyEmail(@RequestParam("email") String email) { - return ResponseUtil.success(userService.sendVerifyEmail(email)); + return Response.success(userService.sendVerifyEmail(email)); } @PostMapping("/emailVerify") public Response emailVerify(@RequestParam("verifyId") String verifyId, @RequestParam("email") String mail) { - return ResponseUtil.success(userService.verifyEmail(verifyId, mail)); + return Response.success(userService.verifyEmail(verifyId, mail)); } @PostMapping("/resetPwd") public Response resetPwd(@RequestParam("verifyId") String verifyId, @RequestParam("email") String email, @RequestParam("pwd") String pwd) { - return ResponseUtil.success(userService.reSetPwd(verifyId, email, pwd)); + return Response.success(userService.reSetPwd(verifyId, email, pwd)); } @PostMapping("/user/setPwd") public Response setPwd(@RequestParam("pwd") String pwd, - @RequestParam("newPwd") String newPwd, - @RequestParam("confirmPwd") String confirmPwd) { - return ResponseUtil.success(userService.setPwd(pwd,newPwd,confirmPwd)); + @RequestParam("newPwd") String newPwd, + @RequestParam("confirmPwd") String confirmPwd) { + return Response.success(userService.setPwd(pwd, newPwd, confirmPwd)); } @DeleteMapping("/admin/user/delete") public Response multipleDelete(@RequestBody Integer[] ids) { - return ResponseUtil.success(userService.deleteUser(ids)); + return Response.success(userService.deleteUser(ids)); } @DeleteMapping("/admin/user/delete/{id}") public Response delete(@PathVariable("id") Integer id) { - return ResponseUtil.success(userService.deleteUser(new Integer[]{id})); + return Response.success(userService.deleteUser(new Integer[]{id})); } @PutMapping("/admin/user") public Response updateInfoByAdmin(@RequestBody UserReq user) { - return ResponseUtil.success(userService.adminUpdate(user)); + return Response.success(userService.adminUpdate(user)); } @GetMapping("/admin/users") public Response getAllUser(@RequestParam("page") int pageNum, @RequestParam("count") int count) { - return ResponseUtil.success(userService.getUserList(pageNum, count)); + return Response.success(userService.getUserList(pageNum, count)); } @GetMapping("/emailStatus/{email}") public Response getEmailStatus(@PathVariable("email") String email) { - return ResponseUtil.success(userService.getStatusOfEmail(email)); + return Response.success(userService.getStatusOfEmail(email)); } diff --git a/src/main/java/cn/celess/blog/controller/VisitorController.java b/src/main/java/cn/celess/blog/controller/VisitorController.java index 741e8ef..8a965f9 100644 --- a/src/main/java/cn/celess/blog/controller/VisitorController.java +++ b/src/main/java/cn/celess/blog/controller/VisitorController.java @@ -3,7 +3,6 @@ package cn.celess.blog.controller; import cn.celess.blog.entity.Response; import cn.celess.blog.service.CountService; import cn.celess.blog.service.VisitorService; -import cn.celess.blog.util.ResponseUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -22,29 +21,29 @@ public class VisitorController { @GetMapping("/visitor/count") public Response getVisitorCount() { - return ResponseUtil.success(countService.getVisitorCount()); + return Response.success(countService.getVisitorCount()); } @GetMapping("/admin/visitor/page") public Response page(@RequestParam(value = "count", required = false, defaultValue = "10") int count, @RequestParam(value = "page", required = false, defaultValue = "1") int page, @RequestParam(value = "showLocation", required = false, defaultValue = "false") boolean showLocation) { - return ResponseUtil.success(visitorService.visitorPage(page, count, showLocation)); + return Response.success(visitorService.visitorPage(page, count, showLocation)); } @PostMapping("/visit") public Response add(HttpServletRequest request) { - return ResponseUtil.success(visitorService.addVisitor(request)); + return Response.success(visitorService.addVisitor(request)); } @GetMapping("/dayVisitCount") public Response dayVisitCount() { - return ResponseUtil.success(countService.getDayVisitCount()); + return Response.success(countService.getDayVisitCount()); } @GetMapping("/ip/{ip}") public Response ipLocation(@PathVariable("ip") String ip) { - return ResponseUtil.success(visitorService.location(ip)); + return Response.success(visitorService.location(ip)); } /** @@ -55,6 +54,6 @@ public class VisitorController { */ @GetMapping("/ip") public Response getIp(HttpServletRequest request) { - return ResponseUtil.success(request.getRemoteAddr()); + return Response.success(request.getRemoteAddr()); } } diff --git a/src/main/java/cn/celess/blog/controller/WebUpdateInfoController.java b/src/main/java/cn/celess/blog/controller/WebUpdateInfoController.java index eb5f432..03e4baa 100644 --- a/src/main/java/cn/celess/blog/controller/WebUpdateInfoController.java +++ b/src/main/java/cn/celess/blog/controller/WebUpdateInfoController.java @@ -2,7 +2,6 @@ package cn.celess.blog.controller; import cn.celess.blog.entity.Response; import cn.celess.blog.service.WebUpdateInfoService; -import cn.celess.blog.util.ResponseUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -17,31 +16,32 @@ public class WebUpdateInfoController { @PostMapping("/admin/webUpdate/create") public Response create(@RequestParam("info") String info) { - return ResponseUtil.success(webUpdateInfoService.create(info)); + return Response.success(webUpdateInfoService.create(info)); } @DeleteMapping("/admin/webUpdate/del/{id}") public Response del(@PathVariable("id") long id) { - return ResponseUtil.success(webUpdateInfoService.del(id)); + return Response.success(webUpdateInfoService.del(id)); } @PutMapping("/admin/webUpdate/update") public Response update(@RequestParam("id") long id, @RequestParam("info") String info) { - return ResponseUtil.success(webUpdateInfoService.update(id, info)); + return Response.success(webUpdateInfoService.update(id, info)); } @GetMapping("/webUpdate") public Response findAll() { - return ResponseUtil.success(webUpdateInfoService.findAll()); + return Response.success(webUpdateInfoService.findAll()); } @GetMapping("/webUpdate/pages") public Response page(@RequestParam("page") int page, @RequestParam("count") int count) { - return ResponseUtil.success(webUpdateInfoService.pages(count, page)); + return Response.success(webUpdateInfoService.pages(count, page)); } + @GetMapping("/lastestUpdate") public Response lastestUpdateTime() { - return ResponseUtil.success(webUpdateInfoService.getLastestUpdateTime()); + return Response.success(webUpdateInfoService.getLastestUpdateTime()); } diff --git a/src/main/java/cn/celess/blog/exception/ExceptionHandle.java b/src/main/java/cn/celess/blog/exception/ExceptionHandle.java index 480a686..a35ab64 100644 --- a/src/main/java/cn/celess/blog/exception/ExceptionHandle.java +++ b/src/main/java/cn/celess/blog/exception/ExceptionHandle.java @@ -26,12 +26,11 @@ import javax.servlet.http.HttpServletRequest; @ControllerAdvice public class ExceptionHandle { + public static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class); @Autowired MailService mailService; @Autowired HttpServletRequest request; - public static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class); - @Value("${spring.profiles.active}") private String activeModel; @@ -41,27 +40,27 @@ public class ExceptionHandle { //自定义错误 if (e instanceof MyException) { logger.debug("返回了自定义的exception,[code={},msg={}]", ((MyException) e).getCode(), e.getMessage()); - return new Response(((MyException) e).getCode(), e.getMessage(), null, System.currentTimeMillis()); + return new Response(((MyException) e).getCode(), e.getMessage(), null); } //请求路径不支持该方法 if (e instanceof HttpRequestMethodNotSupportedException) { - logger.debug("遇到请求路径与请求方法不匹配的请求,[msg={},path:{},method:{}]", e.getMessage(),request.getRequestURL(),request.getMethod()); - return new Response(ResponseEnum.ERROR.getCode(), e.getMessage(), null, System.currentTimeMillis()); + logger.debug("遇到请求路径与请求方法不匹配的请求,[msg={},path:{},method:{}]", e.getMessage(), request.getRequestURL(), request.getMethod()); + return new Response(ResponseEnum.ERROR.getCode(), e.getMessage(), null); } //数据输入类型不匹配 if (e instanceof MethodArgumentTypeMismatchException) { logger.debug("输入类型不匹配,[msg={}]", e.getMessage()); - return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改后再访问", null, System.currentTimeMillis()); + return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改后再访问", null); } //数据验证失败 if (e instanceof BindException) { logger.debug("数据验证失败,[msg={}]", e.getMessage()); - return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改", null, System.currentTimeMillis()); + return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改", null); } //数据输入不完整 if (e instanceof MissingServletRequestParameterException) { logger.debug("数据输入不完整,[msg={}]", e.getMessage()); - return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入不完整,请检查", null, System.currentTimeMillis()); + return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入不完整,请检查", null); } // 发送错误信息到邮箱 @@ -70,7 +69,7 @@ public class ExceptionHandle { sendMessage(e); } e.printStackTrace(); - return new Response(ResponseEnum.ERROR.getCode(), "服务器出现错误,已记录", null, System.currentTimeMillis()); + return new Response(ResponseEnum.ERROR.getCode(), "服务器出现错误,已记录", null); } /** diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/UserServiceImpl.java b/src/main/java/cn/celess/blog/service/serviceimpl/UserServiceImpl.java index 02cabb6..0491be3 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/UserServiceImpl.java +++ b/src/main/java/cn/celess/blog/service/serviceimpl/UserServiceImpl.java @@ -2,6 +2,7 @@ package cn.celess.blog.service.serviceimpl; import cn.celess.blog.enmu.ResponseEnum; import cn.celess.blog.enmu.RoleEnum; +import cn.celess.blog.entity.Response; import cn.celess.blog.entity.User; import cn.celess.blog.entity.model.PageData; import cn.celess.blog.entity.model.QiniuResponse; @@ -185,7 +186,7 @@ public class UserServiceImpl implements UserService { user.setAvatarImgUrl(upload.key); userMapper.updateAvatarImgUrl(upload.key, user.getId()); redisUserUtil.set(user); - return ResponseUtil.success(user.getAvatarImgUrl()); + return Response.success(user.getAvatarImgUrl()); } @Override diff --git a/src/main/java/cn/celess/blog/util/ResponseUtil.java b/src/main/java/cn/celess/blog/util/ResponseUtil.java deleted file mode 100644 index 0cf49e5..0000000 --- a/src/main/java/cn/celess/blog/util/ResponseUtil.java +++ /dev/null @@ -1,59 +0,0 @@ -package cn.celess.blog.util; - -import cn.celess.blog.enmu.ResponseEnum; -import cn.celess.blog.entity.Response; -import org.springframework.web.bind.annotation.ResponseBody; - -/** - * @author : xiaohai - * @date : 2019/03/28 15:32 - */ -@ResponseBody -public class ResponseUtil { - - /** - * 成功相应 - * - * @param result 结果 - * @return - */ - public static Response success(Object result) { - Response response = new Response(); - response.setCode(ResponseEnum.SUCCESS.getCode()); - response.setMsg(ResponseEnum.SUCCESS.getMsg()); - response.setDate(System.currentTimeMillis()); - response.setResult(result); - return response; - } - - /** - * 失败的响应 - * - * @param result 结果 - * @return - */ - public static Response failure(String result) { - Response response = new Response(); - response.setCode(ResponseEnum.FAILURE.getCode()); - response.setMsg(ResponseEnum.FAILURE.getMsg()); - response.setDate(System.currentTimeMillis()); - response.setResult(result); - return response; - } - - /** - * 其他的响应 - * - * @param r 枚举常量 - * @param result 结果 - * @return - */ - public static Response response(ResponseEnum r, String result) { - Response response = new Response(); - response.setCode(r.getCode()); - response.setMsg(r.getMsg()); - response.setDate(System.currentTimeMillis()); - response.setResult(result); - return response; - } -} From 4770c37f4fc980d5257342ae4d4e306b8396216a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Tue, 26 May 2020 14:00:17 +0800 Subject: [PATCH 29/33] =?UTF-8?q?=E4=BF=AE=E6=94=B9Response?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/cn/celess/blog/entity/Response.java | 36 +++++++++++++++++-- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/src/main/java/cn/celess/blog/entity/Response.java b/src/main/java/cn/celess/blog/entity/Response.java index f2fa23f..547ac79 100644 --- a/src/main/java/cn/celess/blog/entity/Response.java +++ b/src/main/java/cn/celess/blog/entity/Response.java @@ -1,5 +1,6 @@ package cn.celess.blog.entity; +import cn.celess.blog.enmu.ResponseEnum; import lombok.Data; import net.sf.json.JSONObject; @@ -14,16 +15,45 @@ public class Response implements Serializable { private int code; private String msg; private Object result; - private long date; public Response() { } - public Response(int code, String msg, Object result, long date) { + public Response(int code, String msg, Object result) { this.code = code; this.msg = msg; this.result = result; - this.date = date; + } + + /** + * 成功相应 + * + * @param result 结果 + * @return Response + */ + public static Response success(Object result) { + return new Response(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), result); + } + + /** + * 失败的响应 + * + * @param result 结果 + * @return Response + */ + public static Response failure(String result) { + return new Response(ResponseEnum.FAILURE.getCode(), ResponseEnum.FAILURE.getMsg(), result); + } + + /** + * 其他的响应 + * + * @param r 枚举常量 + * @param result 结果 + * @return Response + */ + public static Response response(ResponseEnum r, String result) { + return new Response(r.getCode(), r.getMsg(), result); } @Override From 7d7a0fc82dff35540b822dd804af98ef9bb222a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Tue, 26 May 2020 14:01:27 +0800 Subject: [PATCH 30/33] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AF=B9=E8=B1=A1?= =?UTF-8?q?=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/cn/celess/blog/entity/PartnerSite.java | 2 +- src/main/java/cn/celess/blog/entity/TagCategory.java | 4 ++-- .../blog/service/serviceimpl/ArticleServiceImpl.java | 8 +++++++- .../blog/service/serviceimpl/PartnerSiteServiceImpl.java | 4 +++- src/main/java/cn/celess/blog/util/ModalTrans.java | 6 ++++++ src/main/resources/mapper/WebUpdateInfoMapper.xml | 1 + .../java/cn/celess/blog/mapper/CategoryMapperTest.java | 8 ++++---- .../java/cn/celess/blog/mapper/PartnerMapperTest.java | 2 +- src/test/java/cn/celess/blog/mapper/TagMapperTest.java | 6 +++--- 9 files changed, 28 insertions(+), 13 deletions(-) diff --git a/src/main/java/cn/celess/blog/entity/PartnerSite.java b/src/main/java/cn/celess/blog/entity/PartnerSite.java index 40ae597..a45c477 100644 --- a/src/main/java/cn/celess/blog/entity/PartnerSite.java +++ b/src/main/java/cn/celess/blog/entity/PartnerSite.java @@ -23,7 +23,7 @@ public class PartnerSite { private String desc; - private boolean delete; + private Boolean delete = false; public PartnerSite() { } diff --git a/src/main/java/cn/celess/blog/entity/TagCategory.java b/src/main/java/cn/celess/blog/entity/TagCategory.java index e8c0a16..78ec3ed 100644 --- a/src/main/java/cn/celess/blog/entity/TagCategory.java +++ b/src/main/java/cn/celess/blog/entity/TagCategory.java @@ -13,7 +13,7 @@ public class TagCategory { private String name; - private boolean category = true; + private Boolean category = true; - private boolean deleted = false; + private Boolean deleted = false; } diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/ArticleServiceImpl.java b/src/main/java/cn/celess/blog/service/serviceimpl/ArticleServiceImpl.java index 68ae080..ecb1b92 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/ArticleServiceImpl.java +++ b/src/main/java/cn/celess/blog/service/serviceimpl/ArticleServiceImpl.java @@ -321,7 +321,10 @@ public class ArticleServiceImpl implements ArticleService { open.forEach(article -> { ArticleModel model = ModalTrans.article(article, true); model.setTags(null); - setPreAndNextArticle(model); + // setPreAndNextArticle(model); + model.setNextArticle(null); + model.setPreArticle(null); + modelList.add(model); }); return new PageData(new PageInfo
(open), modelList); } @@ -337,6 +340,9 @@ public class ArticleServiceImpl implements ArticleService { List modelList = new ArrayList<>(); articleByTag.forEach(articleTag -> { ArticleModel model = ModalTrans.article(articleTag.getArticle(), true); + model.setNextArticle(null); + model.setPreArticle(null); + modelList.add(model); }); return new PageData(new PageInfo(articleByTag), modelList); } diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/PartnerSiteServiceImpl.java b/src/main/java/cn/celess/blog/service/serviceimpl/PartnerSiteServiceImpl.java index 9bcf5b8..992b7b0 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/PartnerSiteServiceImpl.java +++ b/src/main/java/cn/celess/blog/service/serviceimpl/PartnerSiteServiceImpl.java @@ -97,7 +97,9 @@ public class PartnerSiteServiceImpl implements PartnerSiteService { @Override public List findAll() { - return partnerMapper.findAll(); + List all = partnerMapper.findAll(); + all.forEach(partnerSite -> partnerSite.setDelete(null)); + return all; } diff --git a/src/main/java/cn/celess/blog/util/ModalTrans.java b/src/main/java/cn/celess/blog/util/ModalTrans.java index a8c817f..22c6eec 100644 --- a/src/main/java/cn/celess/blog/util/ModalTrans.java +++ b/src/main/java/cn/celess/blog/util/ModalTrans.java @@ -22,6 +22,10 @@ public class ModalTrans { articleModel.setOriginal(article.getType()); articleModel.setCategory(article.getCategory().getName()); articleModel.setAuthor(user(article.getUser())); + articleModel.getTags().forEach(tag -> { + tag.setCategory(null); + tag.setDeleted(null); + }); return articleModel; } @@ -46,6 +50,8 @@ public class ModalTrans { userModel.setAvatarImgUrl(user.getAvatarImgUrl() == null || user.getAvatarImgUrl().length() == 0 ? null : "http://cdn.celess.cn/" + user.getAvatarImgUrl()); + userModel.setRole(null); + userModel.setEmailStatus(null); userModel.setDisplayName(user.getDisplayName() == null ? user.getEmail() : user.getDisplayName()); userModel.setRecentlyLandedDate(DateFormatUtil.get(user.getRecentlyLandedDate())); return userModel; diff --git a/src/main/resources/mapper/WebUpdateInfoMapper.xml b/src/main/resources/mapper/WebUpdateInfoMapper.xml index 4f42e4e..eb0094e 100644 --- a/src/main/resources/mapper/WebUpdateInfoMapper.xml +++ b/src/main/resources/mapper/WebUpdateInfoMapper.xml @@ -37,6 +37,7 @@ select * from commentView - where pagePath = #{pagePath} + + where pagePath = #{pagePath} + + select count(*) - from article + from comment where is_delete = false; diff --git a/src/main/resources/mapper/articleMapper.xml b/src/main/resources/mapper/articleMapper.xml index 275a0b4..14b07e9 100644 --- a/src/main/resources/mapper/articleMapper.xml +++ b/src/main/resources/mapper/articleMapper.xml @@ -155,7 +155,6 @@ select * from articleView where isDelete = false - order by articleId desc From 2ef9073650f05244f90bc3be6c4c3235eab28c43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Wed, 27 May 2020 16:30:17 +0800 Subject: [PATCH 33/33] =?UTF-8?q?=E8=B0=83=E6=95=B4=E8=AF=84=E8=AE=BA?= =?UTF-8?q?=E7=9A=84=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- blog.sql | 3 +-- .../celess/blog/enmu/CommentStatusEnum.java | 10 ++++++++- .../java/cn/celess/blog/entity/Comment.java | 2 +- .../cn/celess/blog/mapper/CommentMapper.java | 2 +- .../serviceimpl/CommentServiceImpl.java | 12 ++++++++--- src/main/resources/mapper/CommentMapper.xml | 21 +++++++++---------- .../celess/blog/mapper/CommentMapperTest.java | 7 ++++--- 7 files changed, 35 insertions(+), 22 deletions(-) diff --git a/blog.sql b/blog.sql index dc04e28..5e15303 100644 --- a/blog.sql +++ b/blog.sql @@ -47,8 +47,7 @@ CREATE TABLE `comment` `co_status` tinyint not null default 0 comment '评论的状态', `co_pid` bigint not null default -1 comment '评论/留言的父id', `co_from_author_id` int not null comment '留言者id', - `co_to_author_id` int default null comment '父评论的作者id', - `is_delete` boolean not null default false comment '该数据是否被删除' + `co_to_author_id` int default null comment '父评论的作者id' ) DEFAULT CHARSET = utf8mb4 COLLATE utf8mb4_general_ci,comment '评论/留言表'; diff --git a/src/main/java/cn/celess/blog/enmu/CommentStatusEnum.java b/src/main/java/cn/celess/blog/enmu/CommentStatusEnum.java index be1ef88..01ccbac 100644 --- a/src/main/java/cn/celess/blog/enmu/CommentStatusEnum.java +++ b/src/main/java/cn/celess/blog/enmu/CommentStatusEnum.java @@ -1,15 +1,23 @@ package cn.celess.blog.enmu; +import lombok.Getter; + /** * @Author: 小海 * @Date: 2020-05-25 08:58 * @Desc: */ +@Getter public enum CommentStatusEnum { // 正常 - NORMAL(0, "正常"); + NORMAL(0, "正常"), + DELETED(3, "已删除"); + private final int code; + private final String msg; CommentStatusEnum(int code, String msg) { + this.code = code; + this.msg = msg; } } diff --git a/src/main/java/cn/celess/blog/entity/Comment.java b/src/main/java/cn/celess/blog/entity/Comment.java index 03ce756..0651111 100644 --- a/src/main/java/cn/celess/blog/entity/Comment.java +++ b/src/main/java/cn/celess/blog/entity/Comment.java @@ -30,5 +30,5 @@ public class Comment { */ private Long pid; - private boolean delete; + // private boolean delete; } diff --git a/src/main/java/cn/celess/blog/mapper/CommentMapper.java b/src/main/java/cn/celess/blog/mapper/CommentMapper.java index 09b72e0..84af53a 100644 --- a/src/main/java/cn/celess/blog/mapper/CommentMapper.java +++ b/src/main/java/cn/celess/blog/mapper/CommentMapper.java @@ -36,7 +36,7 @@ public interface CommentMapper { List findAllByPagePathAndFromUser(String pagePath, long userId); - List findAllByPagePathAndPid(String pagePath, long pid); + List findAllByPagePathAndPidAndNormal(String pagePath, long pid); long countByPagePath(String pagePath); diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/CommentServiceImpl.java b/src/main/java/cn/celess/blog/service/serviceimpl/CommentServiceImpl.java index 5dcfecb..141738f 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/CommentServiceImpl.java +++ b/src/main/java/cn/celess/blog/service/serviceimpl/CommentServiceImpl.java @@ -1,5 +1,6 @@ package cn.celess.blog.service.serviceimpl; +import cn.celess.blog.enmu.CommentStatusEnum; import cn.celess.blog.enmu.ResponseEnum; import cn.celess.blog.entity.Comment; import cn.celess.blog.entity.User; @@ -76,7 +77,7 @@ public class CommentServiceImpl implements CommentService { if (b == null) { throw new MyException(ResponseEnum.COMMENT_NOT_EXIST); } - if (b.isDelete()) { + if (b.getStatus() == CommentStatusEnum.DELETED.getCode()) { throw new MyException(ResponseEnum.DATA_IS_DELETED); } commentMapper.delete(id); @@ -99,7 +100,7 @@ public class CommentServiceImpl implements CommentService { @Override public PageData retrievePage(String pagePath, int page, int count) { PageHelper.startPage(page, count); - List list = commentMapper.findAllByPagePathAndPid(pagePath, -1); + List list = commentMapper.findAllByPagePathAndPidAndNormal(pagePath, -1); return pageTrans(list); } @@ -107,7 +108,12 @@ public class CommentServiceImpl implements CommentService { public List retrievePageByPid(long pid) { List allByPagePath = commentMapper.findAllByPid(pid); List commentModels = new ArrayList<>(); - allByPagePath.forEach(comment -> commentModels.add(ModalTrans.comment(comment))); + allByPagePath.forEach(comment -> { + if (comment.getStatus() != CommentStatusEnum.DELETED.getCode()) { + commentModels.add(ModalTrans.comment(comment)); + } + }); + return commentModels; } diff --git a/src/main/resources/mapper/CommentMapper.xml b/src/main/resources/mapper/CommentMapper.xml index b7db9b5..73ae58e 100644 --- a/src/main/resources/mapper/CommentMapper.xml +++ b/src/main/resources/mapper/CommentMapper.xml @@ -10,7 +10,6 @@ - @@ -22,7 +21,6 @@ - @@ -51,13 +49,13 @@ update comment - set is_delete = true + set co_status = 3 where co_id = #{id} update comment - set is_delete = true + set co_status = 3 where co_page_path = #{path} @@ -83,10 +81,11 @@ where pid = #{pid} - select * from commentView - + # 无奈之举 + where pagePath = #{pagePath} @@ -95,20 +94,20 @@ select * from commentView where - + pagePath = #{pagePath} and fromAuthorId = #{userId} - select * from commentView where - + pagePath = #{pagePath} and - pid = #{pid} + pid = #{pid} and status = 0 select count(*) from comment - where is_delete = false; + where co_status = 0; diff --git a/src/test/java/cn/celess/blog/mapper/CommentMapperTest.java b/src/test/java/cn/celess/blog/mapper/CommentMapperTest.java index 3c78167..d411dfa 100644 --- a/src/test/java/cn/celess/blog/mapper/CommentMapperTest.java +++ b/src/test/java/cn/celess/blog/mapper/CommentMapperTest.java @@ -1,6 +1,7 @@ package cn.celess.blog.mapper; import cn.celess.blog.BaseTest; +import cn.celess.blog.enmu.CommentStatusEnum; import cn.celess.blog.entity.Comment; import cn.celess.blog.entity.User; import org.junit.Test; @@ -35,7 +36,7 @@ public class CommentMapperTest extends BaseTest { Comment comment = generateComment(); assertEquals(1, commentMapper.delete(comment.getId())); Comment commentById = commentMapper.findCommentById(comment.getId()); - assertTrue(commentById.isDelete()); + assertEquals(commentById.getStatus(), CommentStatusEnum.DELETED.getCode()); } @Test @@ -43,7 +44,7 @@ public class CommentMapperTest extends BaseTest { Comment comment = generateComment(); assertTrue(commentMapper.deleteByPagePath(comment.getPagePath()) >= 1); Comment commentById = commentMapper.findCommentById(comment.getId()); - assertTrue(commentById.isDelete()); + assertEquals(commentById.getStatus(), CommentStatusEnum.DELETED.getCode()); } @Test @@ -91,7 +92,7 @@ public class CommentMapperTest extends BaseTest { @Test public void findAllByPagePathAndPid() { Comment comment = generateComment(); - List allByPagePathAndPid = commentMapper.findAllByPagePathAndPid(comment.getPagePath(), comment.getPid()); + List allByPagePathAndPid = commentMapper.findAllByPagePathAndPidAndNormal(comment.getPagePath(), comment.getPid()); assertTrue(allByPagePathAndPid.size() >= 1); allByPagePathAndPid.forEach(comment1 -> { assertEquals(comment.getPagePath(), comment1.getPagePath());