<!-- 插入帖子 -->
<insert id="insertPost" parameterType="com.example.springboot.entity.Forum.Post" useGeneratedKeys="true" keyProperty="id">
INSERT INTO post(user_id,title,content,created_at,updated_at)
VALUES(#{userId}, #{title}, #{content}, NOW(), NOW())
</insert>
<!-- 删除帖子 -->
<delete id="deletePostById" parameterType="int">
DELETE FROM post WHERE id = #{id}
</delete>
<!-- 管理员删除帖子 -->
<select id="selectChildCommentsByParentId" parameterType="int" resultType="com.example.springboot.entity.Forum.Comment">
SELECT
c.id,
c.post_id AS postId,
c.user_id AS userId,
u.username,
c.parent_comment_id AS parentCommentId,
c.content,
c.created_at AS createdAt,
c.updated_at AS updatedAt
FROM comment c
LEFT JOIN user u ON c.user_id = u.id
WHERE c.parent_comment_id = #{parentId}
</select>
<!-- 更新帖子 -->
<update id="updatePost" parameterType="com.example.springboot.entity.Forum.Post">
UPDATE post
SET title = #{title}, content = #{content}, updated_at = NOW()
WHERE id = #{id}
</update>
<!-- 根据id查询帖子(带用户名) -->
<select id="selectPostById" parameterType="int" resultMap="postResultMap">
SELECT
p.id,
p.user_id AS userId,
u.username,
p.title,
p.content,
p.created_at AS createdAt,
p.updated_at AS updatedAt,
IFNULL(like_counts.count, 0) AS likeCount
FROM post p
LEFT JOIN user u ON p.user_id = u.id
LEFT JOIN (
SELECT post_id, COUNT(*) AS count FROM like_post GROUP BY post_id
) like_counts ON like_counts.post_id = p.id
WHERE p.id = #{id}
</select>
<resultMap id="postResultMap" type="com.example.springboot.entity.Forum.Post">
<id property="id" column="id"/>
<result property="userId" column="userId"/>
<result property="username" column="username"/>
<result property="title" column="title"/>
<result property="content" column="content"/>
<result property="createdAt" column="createdAt"/>
<result property="updatedAt" column="updatedAt"/>
<result property="likeCount" column="likeCount"/>
<result property="liked" column="liked"/>
<result property="favorited" column="favorited"/>
</resultMap>
<!-- 配置resultMap对应属性映射到Post实体 -->
<!-- 模糊搜索帖子的标题 -->
<select id="selectPostsByTitleLike" parameterType="string" resultType="com.example.springboot.entity.Forum.Post">
SELECT
p.id,
p.user_id AS userId,
u.username,
p.title,
p.content,
p.created_at AS createdAt,
p.updated_at AS updatedAt
FROM post p
LEFT JOIN user u ON p.user_id = u.id
WHERE p.title LIKE CONCAT('%', #{title}, '%')
ORDER BY p.created_at DESC
</select>
<!-- 新增评论 -->
<insert id="insertComment" parameterType="com.example.springboot.entity.Forum.Comment" useGeneratedKeys="true" keyProperty="id">
INSERT INTO comment(post_id, user_id, parent_comment_id, content, created_at, updated_at)
VALUES(#{postId}, #{userId}, #{parentCommentId}, #{content}, NOW(), NOW())
</insert>
<!-- 删除评论 -->
<delete id="deleteCommentById" parameterType="int">
DELETE FROM comment WHERE id = #{id}
</delete>
<!-- 查询某帖子下所有评论(带用户名) -->
<select id="selectCommentsByPostId" parameterType="int" resultType="com.example.springboot.entity.Forum.Comment">
SELECT
c.id,
c.post_id AS postId,
c.user_id AS userId,
u.username,
c.parent_comment_id AS parentCommentId,
c.content,
c.created_at AS createdAt,
c.updated_at AS updatedAt
FROM comment c
LEFT JOIN user u ON c.user_id = u.id
WHERE c.post_id = #{postId}
ORDER BY c.created_at ASC
</select>
<!-- 点赞 -->
<insert id="insertLikePost" parameterType="com.example.springboot.entity.Forum.LikePost" useGeneratedKeys="true" keyProperty="id">
INSERT INTO like_post(user_id, post_id, created_at) VALUES(#{userId}, #{postId}, NOW())
</insert>
<delete id="deleteLikePost" parameterType="map">
DELETE FROM like_post WHERE user_id = #{userId} AND post_id = #{postId}
</delete>
<select id="selectLikePost" parameterType="map" resultType="com.example.springboot.entity.Forum.LikePost">
SELECT * FROM like_post WHERE user_id = #{userId} AND post_id = #{postId} LIMIT 1
</select>
<!-- 收藏 -->
<insert id="insertFavoritePost" parameterType="com.example.springboot.entity.Forum.FavoritePost" useGeneratedKeys="true" keyProperty="id">
INSERT INTO favorite_post(user_id, post_id, created_at) VALUES(#{userId}, #{postId}, NOW())
</insert>
<delete id="deleteFavoritePost" parameterType="map">
DELETE FROM favorite_post WHERE user_id = #{userId} AND post_id = #{postId}
</delete>
<select id="selectFavoritePost" parameterType="map" resultType="com.example.springboot.entity.Forum.FavoritePost">
SELECT * FROM favorite_post WHERE user_id = #{userId} AND post_id = #{postId} LIMIT 1
</select>
<!-- 举报 -->
<insert id="insertReportPost" parameterType="com.example.springboot.entity.Forum.ReportPost" useGeneratedKeys="true" keyProperty="id">
INSERT INTO report_post(reporter_id, post_id, reason, created_at) VALUES(#{reporterId}, #{postId}, #{reason}, NOW())
</insert>
<select id="selectReportPostsByPostId" parameterType="int" resultType="com.example.springboot.entity.Forum.ReportPost">
SELECT * FROM report_post WHERE post_id = #{postId} ORDER BY created_at DESC
</select>
<!-- 查询某用户的所有帖子 -->
<select id="selectPostsByUserId" parameterType="int" resultType="com.example.springboot.entity.Forum.Post">
SELECT
p.id,
p.user_id AS userId,
u.username,
p.title,
p.content,
p.created_at AS createdAt,
p.updated_at AS updatedAt,
IFNULL(like_counts.count, 0) AS likeCount
FROM post p
LEFT JOIN user u ON p.user_id = u.id
LEFT JOIN (
SELECT post_id, COUNT(*) AS count
FROM like_post
GROUP BY post_id
) like_counts ON like_counts.post_id = p.id
WHERE p.user_id = #{userId}
ORDER BY p.created_at DESC
</select>
<!-- 查询某帖子的点赞数量 -->
<select id="selectLikeCountByPostId" parameterType="int" resultType="int">
SELECT COUNT(*) FROM like_post WHERE post_id = #{postId}
</select>
<!-- 查询用户点赞过的帖子 -->
<select id="selectLikedPostsByUserId" parameterType="int" resultType="com.example.springboot.entity.Forum.Post">
SELECT
p.id,
p.user_id AS userId,
u.username,
p.title,
p.content,
p.created_at AS createdAt,
p.updated_at AS updatedAt
FROM post p
INNER JOIN like_post lp ON p.id = lp.post_id
LEFT JOIN user u ON p.user_id = u.id
WHERE lp.user_id = #{userId}
ORDER BY lp.created_at DESC
</select>
<!-- 查询用户收藏过的帖子 -->
<select id="selectFavoritedPostsByUserId" parameterType="int" resultType="com.example.springboot.entity.Forum.Post">
SELECT
p.id,
p.user_id AS userId,
u.username,
p.title,
p.content,
p.created_at AS createdAt,
p.updated_at AS updatedAt
FROM post p
INNER JOIN favorite_post fp ON p.id = fp.post_id
LEFT JOIN user u ON p.user_id = u.id
WHERE fp.user_id = #{userId}
ORDER BY fp.created_at DESC
</select>
<select id="selectAllReportPosts" resultType="com.example.springboot.entity.Forum.ReportPost">
SELECT
r.id, r.reporter_id AS reporterId, r.post_id AS postId, r.reason, r.created_at AS createdAt,
u.username AS reporterUsername,
p.title AS postTitle
FROM report_post r
LEFT JOIN user u ON r.reporter_id = u.id
LEFT JOIN post p ON r.post_id = p.id
ORDER BY r.created_at DESC
</select>
<select id="selectNotificationsByUserId" resultType="com.example.springboot.entity.Notification">
SELECT id, user_id AS userId, type, title, content, status, created_at AS createdAt
FROM notification
WHERE user_id = #{userId}
ORDER BY created_at DESC
LIMIT #{offset}, #{limit}
</select>
<select id="selectUnreadCountByUserId" resultType="int">
SELECT COUNT(*)
FROM notification
WHERE user_id = #{userId} AND status = 'UNREAD'
</select>
<update id="updateStatusToRead" parameterType="int">
UPDATE notification
SET status = 'READ'
WHERE id = #{notificationId}
</update>
帖子管理
o 发布帖子
o 通过 POST /forum/post , 提交帖子内容(Post对象)。
o Controller 调用 ForumService.createPost(post),Service 调用 Mapper 插入数据库。
o 删除帖子
o 通过 DELETE /forum/post/{id} 删除帖子。
o 业务层需要验证是否是本人帖子(代码注释提到需在业务层判断,实际逻辑可能在Service补充)。
o 修改帖子
o 通过 PUT /forum/post 提交修改后的帖子(Post对象)。
o Service 执行更新帖子内容。
o 查询帖子
o 按帖子ID查询详细信息:GET /forum/post/{id}。
o 根据标题模糊查询帖子列表:GET /forum/posts?title=xxx。
o 查询某用户的所有帖子(包括附加点赞和收藏状态):GET /forum/user/{userId}/posts。
o 帖子点赞和收藏
o 点赞帖子:POST /forum/post/like,提交点赞数据(LikePost)。
o 取消点赞:DELETE /forum/post/like?userId=xxx&postId=xxx。
o 收藏帖子:POST /forum/post/favorite,提交收藏信息。
o 取消收藏:DELETE /forum/post/favorite?userId=xxx&postId=xxx。
o 查询当前帖子点赞和收藏状态:分别通过GET /forum/post/like/status和GET /forum/post/favorite/status。
o 查询用户点赞过或收藏过的帖子列表。
o 评论管理
o 新增评论:POST /forum/comment。
o 删除评论:DELETE /forum/comment/{id},业务层通常需要验证是否本人评论。
o 获取帖子所有评论(含回复):GET /forum/comments/{postId}。
o 举报帖子
o 举报:POST /forum/post/report,提交举报内容。
o 只能举报帖子,不能举报评论(从接口看)。
业务层细节
o 对帖子、评论进行权限控制(本人操作校验)需写在 Service 层,Controller 目前实现简单返回。
o 点赞和收藏存在去重逻辑,避免重复点赞/收藏。
o 查询帖子的详细信息时,包含点赞数、是否点赞、是否收藏状态(基于当前登录用户)。
o 查询用户的帖子列表时,也补充了点赞和收藏信息。
帖子管理
o 删除帖子
o 管理员可删除任意帖子(删除帖子接口同用,但业务层需要额外判断权限,或者有单独接口,目前delete接口未体现管理员区别)。
o 查看举报
o GET /forum/post/reports:查看所有举报帖子列表。
o GET /forum/post/reports/{postId}:查看指定帖子的举报详情。
o 处理举报
o 目前代码中并无举报处理接口,但管理员会通过查看举报列表来决定后续处理,比如删除帖子等。
o 删除评论(包括子评论)
o DELETE /forum/admin/comment/{id},递归删除该评论及其所有子评论。
o 普通用户只能删除自己评论,管理员可直接调用此接口删除任意评论及其子评论。
<insert id="insertFavoritePost" parameterType="com.example.springboot.entity.Forum.FavoritePost" useGeneratedKeys="true" keyProperty="id">
INSERT INTO favorite_post(user_id, post_id, created_at) VALUES(#{userId}, #{postId}, NOW())
</insert>
<delete id="deleteFavoritePost" parameterType="map">
DELETE FROM favorite_post WHERE user_id = #{userId} AND post_id = #{postId}
</delete>
<select id="selectFavoritePost" parameterType="map" resultType="com.example.springboot.entity.Forum.FavoritePost">
SELECT * FROM favorite_post WHERE user_id = #{userId} AND post_id = #{postId} LIMIT 1
</select>
<select id="selectFavoritedPostsByUserId" parameterType="int" resultType="com.example.springboot.entity.Forum.Post">
SELECT
p.id,
p.user_id AS userId,
u.username,
p.title,
p.content,
p.created_at AS createdAt,
p.updated_at AS updatedAt
FROM post p
INNER JOIN favorite_post fp ON p.id = fp.post_id
LEFT JOIN user u ON p.user_id = u.id
WHERE fp.user_id = #{userId}
ORDER BY fp.created_at DESC
</select>
<!-- 引用点赞和收藏相关相关SQL已存在,不再重复 -->
5. 前端调用示例 (基于Fetch API)
javascript
const userId = 123; // 当前登录用户ID
const postId = 456; // 当前帖子ID
// 收藏帖子
async function favoritePost() {
const res = await fetch('/forum/post/favorite', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({userId, postId})
});
const text = await res.text();
console.log(text); // 收藏成功 或 收藏失败或已收藏
refreshFavoriteStatus();
}
// 取消收藏
async function unfavoritePost() {
const res = await fetch(`/forum/post/favorite?userId=${userId}&postId=${postId}`, {
method: 'DELETE'
});
const text = await res.text();
console.log(text);
refreshFavoriteStatus();
}
// 查询收藏状态
async function fetchFavoriteStatus() {
const res = await fetch(`/forum/post/favorite/status?userId=${userId}&postId=${postId}`);
const data = await res.json();
console.log('收藏状态:', data.favorited);
// 根据状态更新UI按钮
}
// 获取收藏帖子列表示例
async function fetchFavoritedPosts() {
const res = await fetch(`/forum/user/${userId}/favorited-posts`);
const posts = await res.json();
console.log(posts);
// 渲染收藏帖子列表
}
// 在界面调用如下函数刷新状态示例
function refreshFavoriteStatus() {
fetchFavoriteStatus();
// 可同时刷新帖子列表或详情点赞收藏状态
}
查看收藏列表
用户访问“我的收藏”页面,前端调用 GET /forum/user/{userId}/favorited-posts,
后端返回该用户收藏的帖子列表(含点赞数与点赞、收藏状态)。
前端渲染帖子及操作按钮。
X.4 核心代码
1. 控制层 — ForumController.java
java
@RestController
@RequestMapping("/forum")
public class ForumController {
@Resource
private ForumService forumService;
/**
* 收藏帖子接口
*/
@PostMapping("/post/favorite")
public String favoritePost(@RequestBody FavoritePost favoritePost) {
int result = forumService.createFavoritePost(favoritePost);
return result > 0 ? "收藏成功" : "收藏失败或已收藏";
}
/**
* 取消收藏接口
*/
@DeleteMapping("/post/favorite")
public String unfavoritePost(@RequestParam Integer userId, @RequestParam Integer postId) {
int result = forumService.deleteFavoritePost(userId, postId);
return result > 0 ? "取消收藏成功" : "取消收藏失败";
}
/**
* 查询收藏状态接口
*/
@GetMapping("/post/favorite/status")
public Map<String, Boolean> getFavoriteStatus(@RequestParam Integer userId, @RequestParam Integer postId) {
boolean favorited = forumService.getFavoritePost(userId, postId) != null;
return Collections.singletonMap("favorited", favorited);
}
/**
* 获取用户收藏帖子列表接口
*/
@GetMapping("/user/{userId}/favorited-posts")
public List<Post> getFavoritedPostsByUserId(@PathVariable Integer userId) {
return forumService.getFavoritedPostsByUserId(userId);
}
}
2. 业务层 — ForumService.java
java
@Service
public class ForumService {
@Resource
private ForumMapper forumMapper;
/**
* 创建收藏,重复收藏返回0
*/
public int createFavoritePost(FavoritePost favoritePost) {
FavoritePost exist = forumMapper.selectFavoritePost(favoritePost.getUserId(), favoritePost.getPostId());
if (exist != null) return 0;
return forumMapper.insertFavoritePost(favoritePost);
}
/**
* 取消收藏
*/
public int deleteFavoritePost(Integer userId, Integer postId) {
return forumMapper.deleteFavoritePost(userId, postId);
}
/**
* 查询是否收藏
*/
public FavoritePost getFavoritePost(Integer userId, Integer postId) {
return forumMapper.selectFavoritePost(userId, postId);
}
/**
* 查询用户收藏的帖子列表并附加点赞和收藏状态
*/
public List<Post> getFavoritedPostsByUserId(Integer userId) {
List<Post> posts = forumMapper.selectFavoritedPostsByUserId(userId);
enrichPostsWithLikeFavorite(userId, posts);
return posts;
}
/**
* 补全帖子列表的点赞数、点赞状态和收藏状态
*/
private void enrichPostsWithLikeFavorite(Integer userId, List<Post> posts) {
if (posts == null || posts.isEmpty()) return;
for (Post post : posts) {
int likeCount = forumMapper.selectLikeCountByPostId(post.getId());
post.setLikeCount(likeCount);
LikePost likePost = forumMapper.selectLikePost(userId, post.getId());
post.setLiked(likePost != null);
// 收藏列表的帖子默认已收藏,避免重复查询
post.setFavorited(true);
}
}
}
3. 持久层接口 — ForumMapper.java
java
public interface ForumMapper {
int insertFavoritePost(FavoritePost favoritePost);
int deleteFavoritePost(@Param("userId") Integer userId, @Param("postId") Integer postId);
FavoritePost selectFavoritePost(@Param("userId") Integer userId, @Param("postId") Integer postId);
List<Post> selectFavoritedPostsByUserId(@Param("userId") Integer userId);
int selectLikeCountByPostId(@Param("postId") Integer postId);
LikePost selectLikePost(@Param("userId") Integer userId, @Param("postId") Integer postId);
}
4. MyBatis映射文件 — ForumMapper.xml
xml
<insert id="insertFavoritePost" parameterType="com.example.springboot.entity.Forum.FavoritePost" useGeneratedKeys="true" keyProperty="id">
INSERT INTO favorite_post(user_id, post_id, created_at)
VALUES(#{userId}, #{postId}, NOW())
</insert>
<delete id="deleteFavoritePost" parameterType="map">
DELETE FROM favorite_post WHERE user_id = #{userId} AND post_id = #{postId}
</delete>
<select id="selectFavoritePost" parameterType="map" resultType="com.example.springboot.entity.Forum.FavoritePost">
SELECT * FROM favorite_post WHERE user_id = #{userId} AND post_id = #{postId} LIMIT 1
</select>
<select id="selectFavoritedPostsByUserId" parameterType="int" resultType="com.example.springboot.entity.Forum.Post">
SELECT
p.id,
p.user_id AS userId,
u.username,
p.title,
p.content,
p.created_at AS createdAt,
p.updated_at AS updatedAt
FROM post p
INNER JOIN favorite_post fp ON p.id = fp.post_id
LEFT JOIN user u ON p.user_id = u.id
WHERE fp.user_id = #{userId}
ORDER BY fp.created_at DESC
</select>
<!-- 其他关于点赞的SQL映射请参照项目现有配置 -->
<!-- 插入帖子 -->
<insert id="insertPost" parameterType="com.example.springboot.entity.Forum.Post" useGeneratedKeys="true" keyProperty="id">
INSERT INTO post(user_id,title,content,created_at,updated_at)
VALUES(#{userId}, #{title}, #{content}, NOW(), NOW())
</insert>
<!-- 删除帖子 -->
<delete id="deletePostById" parameterType="int">
DELETE FROM post WHERE id = #{id}
</delete>
<!-- 管理员删除帖子 -->
<select id="selectChildCommentsByParentId" parameterType="int" resultType="com.example.springboot.entity.Forum.Comment">
SELECT
c.id,
c.post_id AS postId,
c.user_id AS userId,
u.username,
c.parent_comment_id AS parentCommentId,
c.content,
c.created_at AS createdAt,
c.updated_at AS updatedAt
FROM comment c
LEFT JOIN user u ON c.user_id = u.id
WHERE c.parent_comment_id = #{parentId}
</select>
<!-- 更新帖子 -->
<update id="updatePost" parameterType="com.example.springboot.entity.Forum.Post">
UPDATE post
SET title = #{title}, content = #{content}, updated_at = NOW()
WHERE id = #{id}
</update>
<!-- 根据id查询帖子(带用户名) -->
<select id="selectPostById" parameterType="int" resultMap="postResultMap">
SELECT
p.id,
p.user_id AS userId,
u.username,
p.title,
p.content,
p.created_at AS createdAt,
p.updated_at AS updatedAt,
IFNULL(like_counts.count, 0) AS likeCount
FROM post p
LEFT JOIN user u ON p.user_id = u.id
LEFT JOIN (
SELECT post_id, COUNT(*) AS count FROM like_post GROUP BY post_id
) like_counts ON like_counts.post_id = p.id
WHERE p.id = #{id}
</select>
<resultMap id="postResultMap" type="com.example.springboot.entity.Forum.Post">
<id property="id" column="id"/>
<result property="userId" column="userId"/>
<result property="username" column="username"/>
<result property="title" column="title"/>
<result property="content" column="content"/>
<result property="createdAt" column="createdAt"/>
<result property="updatedAt" column="updatedAt"/>
<result property="likeCount" column="likeCount"/>
<result property="liked" column="liked"/>
<result property="favorited" column="favorited"/>
</resultMap>
<!-- 配置resultMap对应属性映射到Post实体 -->
<!-- 模糊搜索帖子的标题 -->
<select id="selectPostsByTitleLike" parameterType="string" resultType="com.example.springboot.entity.Forum.Post">
SELECT
p.id,
p.user_id AS userId,
u.username,
p.title,
p.content,
p.created_at AS createdAt,
p.updated_at AS updatedAt
FROM post p
LEFT JOIN user u ON p.user_id = u.id
WHERE p.title LIKE CONCAT('%', #{title}, '%')
ORDER BY p.created_at DESC
</select>
<!-- 新增评论 -->
<insert id="insertComment" parameterType="com.example.springboot.entity.Forum.Comment" useGeneratedKeys="true" keyProperty="id">
INSERT INTO comment(post_id, user_id, parent_comment_id, content, created_at, updated_at)
VALUES(#{postId}, #{userId}, #{parentCommentId}, #{content}, NOW(), NOW())
</insert>
<!-- 删除评论 -->
<delete id="deleteCommentById" parameterType="int">
DELETE FROM comment WHERE id = #{id}
</delete>
<!-- 查询某帖子下所有评论(带用户名) -->
<select id="selectCommentsByPostId" parameterType="int" resultType="com.example.springboot.entity.Forum.Comment">
SELECT
c.id,
c.post_id AS postId,
c.user_id AS userId,
u.username,
c.parent_comment_id AS parentCommentId,
c.content,
c.created_at AS createdAt,
c.updated_at AS updatedAt
FROM comment c
LEFT JOIN user u ON c.user_id = u.id
WHERE c.post_id = #{postId}
ORDER BY c.created_at ASC
</select>
<!-- 点赞 -->
<insert id="insertLikePost" parameterType="com.example.springboot.entity.Forum.LikePost" useGeneratedKeys="true" keyProperty="id">
INSERT INTO like_post(user_id, post_id, created_at) VALUES(#{userId}, #{postId}, NOW())
</insert>
<delete id="deleteLikePost" parameterType="map">
DELETE FROM like_post WHERE user_id = #{userId} AND post_id = #{postId}
</delete>
<select id="selectLikePost" parameterType="map" resultType="com.example.springboot.entity.Forum.LikePost">
SELECT * FROM like_post WHERE user_id = #{userId} AND post_id = #{postId} LIMIT 1
</select>
<!-- 收藏 -->
<insert id="insertFavoritePost" parameterType="com.example.springboot.entity.Forum.FavoritePost" useGeneratedKeys="true" keyProperty="id">
INSERT INTO favorite_post(user_id, post_id, created_at) VALUES(#{userId}, #{postId}, NOW())
</insert>
<delete id="deleteFavoritePost" parameterType="map">
DELETE FROM favorite_post WHERE user_id = #{userId} AND post_id = #{postId}
</delete>
<select id="selectFavoritePost" parameterType="map" resultType="com.example.springboot.entity.Forum.FavoritePost">
SELECT * FROM favorite_post WHERE user_id = #{userId} AND post_id = #{postId} LIMIT 1
</select>
<!-- 举报 -->
<insert id="insertReportPost" parameterType="com.example.springboot.entity.Forum.ReportPost" useGeneratedKeys="true" keyProperty="id">
INSERT INTO report_post(reporter_id, post_id, reason, created_at) VALUES(#{reporterId}, #{postId}, #{reason}, NOW())
</insert>
<select id="selectReportPostsByPostId" parameterType="int" resultType="com.example.springboot.entity.Forum.ReportPost">
SELECT * FROM report_post WHERE post_id = #{postId} ORDER BY created_at DESC
</select>
<!-- 查询某用户的所有帖子 -->
<select id="selectPostsByUserId" parameterType="int" resultType="com.example.springboot.entity.Forum.Post">
SELECT
p.id,
p.user_id AS userId,
u.username,
p.title,
p.content,
p.created_at AS createdAt,
p.updated_at AS updatedAt,
IFNULL(like_counts.count, 0) AS likeCount
FROM post p
LEFT JOIN user u ON p.user_id = u.id
LEFT JOIN (
SELECT post_id, COUNT(*) AS count
FROM like_post
GROUP BY post_id
) like_counts ON like_counts.post_id = p.id
WHERE p.user_id = #{userId}
ORDER BY p.created_at DESC
</select>
<!-- 查询某帖子的点赞数量 -->
<select id="selectLikeCountByPostId" parameterType="int" resultType="int">
SELECT COUNT(*) FROM like_post WHERE post_id = #{postId}
</select>
<!-- 查询用户点赞过的帖子 -->
<select id="selectLikedPostsByUserId" parameterType="int" resultType="com.example.springboot.entity.Forum.Post">
SELECT
p.id,
p.user_id AS userId,
u.username,
p.title,
p.content,
p.created_at AS createdAt,
p.updated_at AS updatedAt
FROM post p
INNER JOIN like_post lp ON p.id = lp.post_id
LEFT JOIN user u ON p.user_id = u.id
WHERE lp.user_id = #{userId}
ORDER BY lp.created_at DESC
</select>
<!-- 查询用户收藏过的帖子 -->
<select id="selectFavoritedPostsByUserId" parameterType="int" resultType="com.example.springboot.entity.Forum.Post">
SELECT
p.id,
p.user_id AS userId,
u.username,
p.title,
p.content,
p.created_at AS createdAt,
p.updated_at AS updatedAt
FROM post p
INNER JOIN favorite_post fp ON p.id = fp.post_id
LEFT JOIN user u ON p.user_id = u.id
WHERE fp.user_id = #{userId}
ORDER BY fp.created_at DESC
</select>
<select id="selectAllReportPosts" resultType="com.example.springboot.entity.Forum.ReportPost">
SELECT
r.id, r.reporter_id AS reporterId, r.post_id AS postId, r.reason, r.created_at AS createdAt,
u.username AS reporterUsername,
p.title AS postTitle
FROM report_post r
LEFT JOIN user u ON r.reporter_id = u.id
LEFT JOIN post p ON r.post_id = p.id
ORDER BY r.created_at DESC
</select>
@Resource
private ForumMapper forumMapper;
// ---------------- 帖子相关 ---------------- //
public int createPost(Post post) {
return forumMapper.insertPost(post);
}
public int deletePost(Integer postId) {
return forumMapper.deletePostById(postId);
}
public int updatePost(Post post) {
return forumMapper.updatePost(post);
}
/**
* 根据帖子ID查询帖子详情,注意likeCount是从 like_post 表动态统计的,需要你的Mapper支持
* 建议对应 Mapper 查询中联表统计点赞数
*/
public Post getPostById(Integer postId) {
return forumMapper.selectPostById(postId);
}
public List<Post> searchPostsByTitle(String title) {
return forumMapper.selectPostsByTitleLike(title);
}
/**
* 查询某用户的帖子列表
* 建议 SQL 联表统计点赞数
*/
public List<Post> getPostsByUserId(Integer userId) {
List<Post> posts = forumMapper.selectPostsByUserId(userId);
// 补充点赞状态和收藏状态等
enrichPostsWithLikeFavorite(userId, posts);
return posts;
}
// ---------------- 评论相关 ---------------- //
public int createComment(Comment comment) {
return forumMapper.insertComment(comment);
}
public int deleteComment(Integer commentId) {
return forumMapper.deleteCommentById(commentId);
}
public List<Comment> getCommentsByPostId(Integer postId) {
return forumMapper.selectCommentsByPostId(postId);
}
public int adminDeleteComment(Integer commentId) {
List<Comment> children = forumMapper.selectChildCommentsByParentId(commentId);
int count = 0;
for (Comment child : children) {
count += adminDeleteComment(child.getId());
}
count += forumMapper.deleteCommentById(commentId);
return count;
}
// ---------------- 点赞相关 ---------------- //
/**
* 点赞某帖子,重复点赞会返回0表示已点赞
* 只往 like_post 插入记录,不修改 post 表
*/
public int createLikePost(LikePost likePost) {
LikePost exist = forumMapper.selectLikePost(likePost.getUserId(), likePost.getPostId());
if (exist != null) return 0;
return forumMapper.insertLikePost(likePost);
}
/**
* 取消点赞,删除 like_post 记录,不修改 post 表
*/
public int deleteLikePost(Integer userId, Integer postId) {
return forumMapper.deleteLikePost(userId, postId);
}
public LikePost getLikePost(Integer userId, Integer postId) {
return forumMapper.selectLikePost(userId, postId);
}
/**
* 查询某帖子点赞数量,动态查询 like_post 表
*/
public int getLikeCountByPostId(Integer postId) {
return forumMapper.selectLikeCountByPostId(postId);
}
// ---------------- 收藏相关 ---------------- //
public int createFavoritePost(FavoritePost favoritePost) {
FavoritePost exist = forumMapper.selectFavoritePost(favoritePost.getUserId(), favoritePost.getPostId());
if (exist != null) return 0;
return forumMapper.insertFavoritePost(favoritePost);
}
public int deleteFavoritePost(Integer userId, Integer postId) {
return forumMapper.deleteFavoritePost(userId, postId);
}
public FavoritePost getFavoritePost(Integer userId, Integer postId) {
return forumMapper.selectFavoritePost(userId, postId);
}
// ---------------- 举报相关 ---------------- //
public int createReportPost(ReportPost reportPost) {
// 可加重复举报校验,暂略
return forumMapper.insertReportPost(reportPost);
}
public List<ReportPost> getReportPostsByPostId(Integer postId) {
return forumMapper.selectReportPostsByPostId(postId);
}
// ---------------- 用户点赞和收藏的帖子列表 ---------------- //
/**
* 查询用户点赞过的帖子列表
*/
public List<Post> getLikedPostsByUserId(Integer userId) {
List<Post> posts = forumMapper.selectLikedPostsByUserId(userId);
enrichPostsWithLikeFavorite(userId, posts);
return posts;
}
/**
* 查询用户收藏过的帖子列表
*/
public List<Post> getFavoritedPostsByUserId(Integer userId) {
List<Post> posts = forumMapper.selectFavoritedPostsByUserId(userId);
enrichPostsWithLikeFavorite(userId, posts);
return posts;
}
/**
* 给帖子列表补全点赞数,点赞状态,收藏状态
*/
private void enrichPostsWithLikeFavorite(Integer userId, List<Post> posts) {
if (posts == null || posts.isEmpty()) return;
boolean isLikedList = true;
for (Post post : posts) {
int likeCount = forumMapper.selectLikeCountByPostId(post.getId());
post.setLikeCount(likeCount);
if(isLikedList) {
post.setLiked(true); // 对于我点赞的帖子的列表,这里直接赋true
} else {
LikePost likePost = forumMapper.selectLikePost(userId, post.getId());
post.setLiked(likePost != null);
}
FavoritePost favPost = forumMapper.selectFavoritePost(userId, post.getId());
post.setFavorited(favPost != null);
// 如果某个帖子没有点赞,说明不是点赞过帖子列表,退出标记
if(isLikedList && !post.getLiked()){
isLikedList = false;
}
}
}
public List<ReportPost> getAllReportPosts() {
return forumMapper.selectAllReportPosts();
}
<!-- 插入帖子 -->
<insert id="insertPost" parameterType="com.example.springboot.entity.Forum.Post" useGeneratedKeys="true" keyProperty="id">
INSERT INTO post(user_id,title,content,created_at,updated_at)
VALUES(#{userId}, #{title}, #{content}, NOW(), NOW())
</insert>
<!-- 删除帖子 -->
<delete id="deletePostById" parameterType="int">
DELETE FROM post WHERE id = #{id}
</delete>
<!-- 管理员删除帖子 -->
<select id="selectChildCommentsByParentId" parameterType="int" resultType="com.example.springboot.entity.Forum.Comment">
SELECT
c.id,
c.post_id AS postId,
c.user_id AS userId,
u.username,
c.parent_comment_id AS parentCommentId,
c.content,
c.created_at AS createdAt,
c.updated_at AS updatedAt
FROM comment c
LEFT JOIN user u ON c.user_id = u.id
WHERE c.parent_comment_id = #{parentId}
</select>
<!-- 更新帖子 -->
<update id="updatePost" parameterType="com.example.springboot.entity.Forum.Post">
UPDATE post
SET title = #{title}, content = #{content}, updated_at = NOW()
WHERE id = #{id}
</update>
<!-- 根据id查询帖子(带用户名) -->
<select id="selectPostById" parameterType="int" resultMap="postResultMap">
SELECT
p.id,
p.user_id AS userId,
u.username,
p.title,
p.content,
p.created_at AS createdAt,
p.updated_at AS updatedAt,
IFNULL(like_counts.count, 0) AS likeCount
FROM post p
LEFT JOIN user u ON p.user_id = u.id
LEFT JOIN (
SELECT post_id, COUNT(*) AS count FROM like_post GROUP BY post_id
) like_counts ON like_counts.post_id = p.id
WHERE p.id = #{id}
</select>
<resultMap id="postResultMap" type="com.example.springboot.entity.Forum.Post">
<id property="id" column="id"/>
<result property="userId" column="userId"/>
<result property="username" column="username"/>
<result property="title" column="title"/>
<result property="content" column="content"/>
<result property="createdAt" column="createdAt"/>
<result property="updatedAt" column="updatedAt"/>
<result property="likeCount" column="likeCount"/>
<result property="liked" column="liked"/>
<result property="favorited" column="favorited"/>
</resultMap>
<!-- 配置resultMap对应属性映射到Post实体 -->
<!-- 模糊搜索帖子的标题 -->
<select id="selectPostsByTitleLike" parameterType="string" resultType="com.example.springboot.entity.Forum.Post">
SELECT
p.id,
p.user_id AS userId,
u.username,
p.title,
p.content,
p.created_at AS createdAt,
p.updated_at AS updatedAt
FROM post p
LEFT JOIN user u ON p.user_id = u.id
WHERE p.title LIKE CONCAT('%', #{title}, '%')
ORDER BY p.created_at DESC
</select>
<!-- 新增评论 -->
<insert id="insertComment" parameterType="com.example.springboot.entity.Forum.Comment" useGeneratedKeys="true" keyProperty="id">
INSERT INTO comment(post_id, user_id, parent_comment_id, content, created_at, updated_at)
VALUES(#{postId}, #{userId}, #{parentCommentId}, #{content}, NOW(), NOW())
</insert>
<!-- 删除评论 -->
<delete id="deleteCommentById" parameterType="int">
DELETE FROM comment WHERE id = #{id}
</delete>
<!-- 查询某帖子下所有评论(带用户名) -->
<select id="selectCommentsByPostId" parameterType="int" resultType="com.example.springboot.entity.Forum.Comment">
SELECT
c.id,
c.post_id AS postId,
c.user_id AS userId,
u.username,
c.parent_comment_id AS parentCommentId,
c.content,
c.created_at AS createdAt,
c.updated_at AS updatedAt
FROM comment c
LEFT JOIN user u ON c.user_id = u.id
WHERE c.post_id = #{postId}
ORDER BY c.created_at ASC
</select>
<!-- 点赞 -->
<insert id="insertLikePost" parameterType="com.example.springboot.entity.Forum.LikePost" useGeneratedKeys="true" keyProperty="id">
INSERT INTO like_post(user_id, post_id, created_at) VALUES(#{userId}, #{postId}, NOW())
</insert>
<delete id="deleteLikePost" parameterType="map">
DELETE FROM like_post WHERE user_id = #{userId} AND post_id = #{postId}
</delete>
<select id="selectLikePost" parameterType="map" resultType="com.example.springboot.entity.Forum.LikePost">
SELECT * FROM like_post WHERE user_id = #{userId} AND post_id = #{postId} LIMIT 1
</select>
<!-- 收藏 -->
<insert id="insertFavoritePost" parameterType="com.example.springboot.entity.Forum.FavoritePost" useGeneratedKeys="true" keyProperty="id">
INSERT INTO favorite_post(user_id, post_id, created_at) VALUES(#{userId}, #{postId}, NOW())
</insert>
<delete id="deleteFavoritePost" parameterType="map">
DELETE FROM favorite_post WHERE user_id = #{userId} AND post_id = #{postId}
</delete>
<select id="selectFavoritePost" parameterType="map" resultType="com.example.springboot.entity.Forum.FavoritePost">
SELECT * FROM favorite_post WHERE user_id = #{userId} AND post_id = #{postId} LIMIT 1
</select>
<!-- 举报 -->
<insert id="insertReportPost" parameterType="com.example.springboot.entity.Forum.ReportPost" useGeneratedKeys="true" keyProperty="id">
INSERT INTO report_post(reporter_id, post_id, reason, created_at) VALUES(#{reporterId}, #{postId}, #{reason}, NOW())
</insert>
<select id="selectReportPostsByPostId" parameterType="int" resultType="com.example.springboot.entity.Forum.ReportPost">
SELECT * FROM report_post WHERE post_id = #{postId} ORDER BY created_at DESC
</select>
<!-- 查询某用户的所有帖子 -->
<select id="selectPostsByUserId" parameterType="int" resultType="com.example.springboot.entity.Forum.Post">
SELECT
p.id,
p.user_id AS userId,
u.username,
p.title,
p.content,
p.created_at AS createdAt,
p.updated_at AS updatedAt,
IFNULL(like_counts.count, 0) AS likeCount
FROM post p
LEFT JOIN user u ON p.user_id = u.id
LEFT JOIN (
SELECT post_id, COUNT(*) AS count
FROM like_post
GROUP BY post_id
) like_counts ON like_counts.post_id = p.id
WHERE p.user_id = #{userId}
ORDER BY p.created_at DESC
</select>
<!-- 查询某帖子的点赞数量 -->
<select id="selectLikeCountByPostId" parameterType="int" resultType="int">
SELECT COUNT(*) FROM like_post WHERE post_id = #{postId}
</select>
<!-- 查询用户点赞过的帖子 -->
<select id="selectLikedPostsByUserId" parameterType="int" resultType="com.example.springboot.entity.Forum.Post">
SELECT
p.id,
p.user_id AS userId,
u.username,
p.title,
p.content,
p.created_at AS createdAt,
p.updated_at AS updatedAt
FROM post p
INNER JOIN like_post lp ON p.id = lp.post_id
LEFT JOIN user u ON p.user_id = u.id
WHERE lp.user_id = #{userId}
ORDER BY lp.created_at DESC
</select>
<!-- 查询用户收藏过的帖子 -->
<select id="selectFavoritedPostsByUserId" parameterType="int" resultType="com.example.springboot.entity.Forum.Post">
SELECT
p.id,
p.user_id AS userId,
u.username,
p.title,
p.content,
p.created_at AS createdAt,
p.updated_at AS updatedAt
FROM post p
INNER JOIN favorite_post fp ON p.id = fp.post_id
LEFT JOIN user u ON p.user_id = u.id
WHERE fp.user_id = #{userId}
ORDER BY fp.created_at DESC
</select>
<select id="selectAllReportPosts" resultType="com.example.springboot.entity.Forum.ReportPost">
SELECT
r.id, r.reporter_id AS reporterId, r.post_id AS postId, r.reason, r.created_at AS createdAt,
u.username AS reporterUsername,
p.title AS postTitle
FROM report_post r
LEFT JOIN user u ON r.reporter_id = u.id
LEFT JOIN post p ON r.post_id = p.id
ORDER BY r.created_at DESC
</select>
@Resource
private ForumMapper forumMapper;
// ---------------- 帖子相关 ---------------- //
public int createPost(Post post) {
return forumMapper.insertPost(post);
}
public int deletePost(Integer postId) {
return forumMapper.deletePostById(postId);
}
public int updatePost(Post post) {
return forumMapper.updatePost(post);
}
/**
* 根据帖子ID查询帖子详情,注意likeCount是从 like_post 表动态统计的,需要你的Mapper支持
* 建议对应 Mapper 查询中联表统计点赞数
*/
public Post getPostById(Integer postId) {
return forumMapper.selectPostById(postId);
}
public List<Post> searchPostsByTitle(String title) {
return forumMapper.selectPostsByTitleLike(title);
}
/**
* 查询某用户的帖子列表
* 建议 SQL 联表统计点赞数
*/
public List<Post> getPostsByUserId(Integer userId) {
List<Post> posts = forumMapper.selectPostsByUserId(userId);
// 补充点赞状态和收藏状态等
enrichPostsWithLikeFavorite(userId, posts);
return posts;
}
// ---------------- 评论相关 ---------------- //
public int createComment(Comment comment) {
return forumMapper.insertComment(comment);
}
public int deleteComment(Integer commentId) {
return forumMapper.deleteCommentById(commentId);
}
public List<Comment> getCommentsByPostId(Integer postId) {
return forumMapper.selectCommentsByPostId(postId);
}
public int adminDeleteComment(Integer commentId) {
List<Comment> children = forumMapper.selectChildCommentsByParentId(commentId);
int count = 0;
for (Comment child : children) {
count += adminDeleteComment(child.getId());
}
count += forumMapper.deleteCommentById(commentId);
return count;
}
// ---------------- 点赞相关 ---------------- //
/**
* 点赞某帖子,重复点赞会返回0表示已点赞
* 只往 like_post 插入记录,不修改 post 表
*/
public int createLikePost(LikePost likePost) {
LikePost exist = forumMapper.selectLikePost(likePost.getUserId(), likePost.getPostId());
if (exist != null) return 0;
return forumMapper.insertLikePost(likePost);
}
/**
* 取消点赞,删除 like_post 记录,不修改 post 表
*/
public int deleteLikePost(Integer userId, Integer postId) {
return forumMapper.deleteLikePost(userId, postId);
}
public LikePost getLikePost(Integer userId, Integer postId) {
return forumMapper.selectLikePost(userId, postId);
}
/**
* 查询某帖子点赞数量,动态查询 like_post 表
*/
public int getLikeCountByPostId(Integer postId) {
return forumMapper.selectLikeCountByPostId(postId);
}
// ---------------- 收藏相关 ---------------- //
public int createFavoritePost(FavoritePost favoritePost) {
FavoritePost exist = forumMapper.selectFavoritePost(favoritePost.getUserId(), favoritePost.getPostId());
if (exist != null) return 0;
return forumMapper.insertFavoritePost(favoritePost);
}
public int deleteFavoritePost(Integer userId, Integer postId) {
return forumMapper.deleteFavoritePost(userId, postId);
}
public FavoritePost getFavoritePost(Integer userId, Integer postId) {
return forumMapper.selectFavoritePost(userId, postId);
}
// ---------------- 举报相关 ---------------- //
public int createReportPost(ReportPost reportPost) {
// 可加重复举报校验,暂略
return forumMapper.insertReportPost(reportPost);
}
public List<ReportPost> getReportPostsByPostId(Integer postId) {
return forumMapper.selectReportPostsByPostId(postId);
}
// ---------------- 用户点赞和收藏的帖子列表 ---------------- //
/**
* 查询用户点赞过的帖子列表
*/
public List<Post> getLikedPostsByUserId(Integer userId) {
List<Post> posts = forumMapper.selectLikedPostsByUserId(userId);
enrichPostsWithLikeFavorite(userId, posts);
return posts;
}
/**
* 查询用户收藏过的帖子列表
*/
public List<Post> getFavoritedPostsByUserId(Integer userId) {
List<Post> posts = forumMapper.selectFavoritedPostsByUserId(userId);
enrichPostsWithLikeFavorite(userId, posts);
return posts;
}
/**
* 给帖子列表补全点赞数,点赞状态,收藏状态
*/
private void enrichPostsWithLikeFavorite(Integer userId, List<Post> posts) {
if (posts == null || posts.isEmpty()) return;
boolean isLikedList = true;
for (Post post : posts) {
int likeCount = forumMapper.selectLikeCountByPostId(post.getId());
post.setLikeCount(likeCount);
if(isLikedList) {
post.setLiked(true); // 对于我点赞的帖子的列表,这里直接赋true
} else {
LikePost likePost = forumMapper.selectLikePost(userId, post.getId());
post.setLiked(likePost != null);
}
FavoritePost favPost = forumMapper.selectFavoritePost(userId, post.getId());
post.setFavorited(favPost != null);
// 如果某个帖子没有点赞,说明不是点赞过帖子列表,退出标记
if(isLikedList && !post.getLiked()){
isLikedList = false;
}
}
}
public List<ReportPost> getAllReportPosts() {
return forumMapper.selectAllReportPosts();
}