| package com.example.myproject.service; |
| |
| import com.example.myproject.entity.Collections; |
| import com.example.myproject.entity.Likes; |
| import com.example.myproject.entity.Post; |
| import com.example.myproject.entity.Users; |
| import com.example.myproject.repository.CollectionsRepository; |
| import com.example.myproject.repository.LikesRepository; |
| import com.example.myproject.repository.PostRepository; |
| import com.example.myproject.repository.UserRepository; |
| import org.springframework.beans.factory.annotation.Autowired; |
| import org.springframework.stereotype.Service; |
| import org.springframework.transaction.annotation.Transactional; |
| import org.springframework.web.multipart.MultipartFile; |
| import java.io.IOException; |
| import java.nio.file.Files; |
| import java.nio.file.Path; |
| import java.nio.file.Paths; |
| import java.util.*; |
| |
| @Service |
| public class PostService { |
| |
| @Autowired |
| private PostRepository postRepository; |
| |
| @Autowired |
| private UserRepository userRepository; |
| |
| @Autowired |
| private LikesRepository likesRepository; |
| |
| @Autowired |
| private CollectionsRepository collectionsRepository; |
| |
| private static final String IMAGE_DIR = "uploads/post/"; |
| |
| // 创建帖子 - 添加 @Transactional |
| @Transactional |
| public Map<String, Object> createPost(Long userId, String postContent, String title, MultipartFile[] imageFiles) { |
| Users user = userRepository.findById(userId).orElseThrow(() -> new RuntimeException("User not found")); |
| Post post = new Post(); |
| post.setUser_id(user.getUserId()); |
| post.setPostTime(new Date()); |
| post.setPostLikeNum(0); |
| post.setPostCollectNum(0); |
| post.setPostContent(postContent); |
| post.setTitle(title); |
| |
| StringBuilder imageUrlsBuilder = new StringBuilder(); |
| if (imageFiles != null && imageFiles.length > 0) { |
| for (int i = 0; i < imageFiles.length; i++) { |
| if (i > 0) { |
| imageUrlsBuilder.append(","); |
| } |
| try { |
| String imageUrl = saveImage(imageFiles[i]); |
| imageUrlsBuilder.append(imageUrl); |
| } catch (IOException e) { |
| throw new RuntimeException("Image upload failed: " + e.getMessage()); |
| } |
| } |
| } |
| post.setImageUrl(imageUrlsBuilder.toString()); |
| Post savedPost = postRepository.save(post); |
| |
| Map<String, Object> response = new HashMap<>(); |
| response.put("postNo", savedPost.getPostNo()); |
| response.put("message", "帖子创建成功"); |
| return response; |
| } |
| |
| // 保存图片并返回图片的 URL |
| public String saveImage(MultipartFile imageFile) throws IOException { |
| String fileName = imageFile.getOriginalFilename(); |
| Path path = Paths.get(IMAGE_DIR + fileName); |
| Files.createDirectories(path.getParent()); |
| Files.write(path, imageFile.getBytes()); |
| return "/uploads/post/" + fileName; |
| } |
| |
| // 编辑帖子 - 添加 @Transactional |
| @Transactional |
| public void updatePost(Long postId, Post post) { |
| Post existingPost = postRepository.findById(postId).orElseThrow(() -> new RuntimeException("Post not found")); |
| if (post.getTitle() != null) { |
| existingPost.setTitle(post.getTitle()); |
| } |
| if (post.getPostContent() != null) { |
| existingPost.setPostContent(post.getPostContent()); |
| } |
| if (post.getImageUrl() != null) { |
| existingPost.setImageUrl(post.getImageUrl()); |
| } |
| existingPost.setPostTime(post.getPostTime()); |
| postRepository.save(existingPost); |
| } |
| |
| // 删除帖子 - 添加 @Transactional |
| @Transactional |
| public void deletePost(Long postId) { |
| // 查找指定 ID 的帖子,如果不存在则抛出异常 |
| if (!postRepository.existsById(postId)) { |
| throw new RuntimeException("Post not found"); |
| } |
| // 删除该帖子 |
| postRepository.deleteById(postId); |
| } |
| |
| // 点赞帖子 - 添加 @Transactional |
| @Transactional |
| public void likePost(Long postId, Long userId) { |
| // 查找指定 ID 的帖子 |
| Post post = postRepository.findById(postId).orElseThrow(() -> new RuntimeException("Post not found")); |
| post.setPostLikeNum(post.getPostLikeNum() + 1); |
| |
| // 保存帖子 |
| postRepository.save(post); |
| Likes like = new Likes(); |
| like.setUserId(userId); |
| like.setPostNo(postId); |
| // 保存点赞记录 |
| likesRepository.save(like); |
| } |
| |
| // 取消点赞帖子 - 已有 @Transactional |
| @Transactional |
| public void unlikePost(Long postId, Long userId) { |
| // 查找指定 ID 的帖子 |
| Post post = postRepository.findById(postId).orElseThrow(() -> new RuntimeException("Post not found")); |
| |
| // 如果点赞数大于 0,则减少点赞数 |
| if (post.getPostLikeNum() > 0) { |
| post.setPostLikeNum(post.getPostLikeNum() - 1); |
| } |
| |
| // 删除点赞表中对应的记录 |
| likesRepository.deleteLikeByUserIdAndPostNo(userId, postId); |
| |
| // 保存更新后的帖子 |
| postRepository.save(post); |
| } |
| |
| // // 获取帖子列表 - 不需要 @Transactional(只读操作) |
| // public Map<String, Object> getAllPosts() { |
| // List<Post> posts = postRepository.findAll(); |
| // List<Map<String, Object>> postList = new ArrayList<>(); |
| // |
| // for (Post post : posts) { |
| // Map<String, Object> postMap = new LinkedHashMap<>(); |
| // postMap.put("postNo", post.getPostNo()); |
| // postMap.put("user_id", post.getUser_id()); |
| // postMap.put("postContent", post.getPostContent()); |
| // postMap.put("imgUrl", post.getImageUrl()); |
| // postMap.put("title", post.getTitle()); |
| // postMap.put("createdAt", |
| // post.getPostTime() != null ? post.getPostTime().toString() : "未设置"); |
| // |
| // postMap.put("likeCount", post.getPostLikeNum()); |
| // postMap.put("collectCount", post.getPostCollectNum()); |
| // |
| // postList.add(postMap); |
| // } |
| // |
| // Map<String, Object> response = new HashMap<>(); |
| // // 统计帖子数量 |
| // response.put("total", postList.size()); |
| // response.put("posts", postList); |
| // |
| // return response; |
| // } |
| public Map<String, Object> getAllPosts() { |
| List<Post> posts = postRepository.findAll(); |
| List<Map<String, Object>> postList = new ArrayList<>(); |
| |
| for (Post post : posts) { |
| Map<String, Object> postMap = new LinkedHashMap<>(); |
| postMap.put("postNo", post.getPostNo()); |
| postMap.put("user_id", post.getUser_id()); |
| postMap.put("postContent", post.getPostContent()); |
| postMap.put("imgUrl", post.getImageUrl()); |
| postMap.put("title", post.getTitle()); |
| postMap.put("createdAt", |
| post.getPostTime() != null ? post.getPostTime().toString() : "未设置"); |
| |
| postMap.put("likeCount", post.getPostLikeNum()); |
| postMap.put("collectCount", post.getPostCollectNum()); |
| |
| // 查询用户信息 |
| Optional<Users> userOptional = userRepository.findById(post.getUser_id()); |
| if (userOptional.isPresent()) { |
| Users user = userOptional.get(); |
| postMap.put("username", user.getUsername()); |
| postMap.put("avatarUrl", user.getAvatarUrl()); |
| } else { |
| postMap.put("username", "未知用户"); |
| postMap.put("avatarUrl", null); |
| } |
| |
| postList.add(postMap); |
| } |
| |
| Map<String, Object> response = new HashMap<>(); |
| // 统计帖子数量 |
| response.put("total", postList.size()); |
| response.put("posts", postList); |
| |
| return response; |
| } |
| |
| |
| // 获取单个帖子 - 不需要 @Transactional(只读操作) |
| public Map<String, Object> getPostById(Long postId) { |
| Optional<Post> postOptional = postRepository.findById(postId); |
| |
| if (postOptional.isPresent()) { |
| Post post = postOptional.get(); |
| Map<String, Object> postData = new LinkedHashMap<>(); |
| postData.put("postNo", post.getPostNo()); |
| postData.put("user_id", post.getUser_id()); |
| Long userId = post.getUser_id(); |
| Users user = userRepository.findById(userId).orElse(null); |
| |
| if (user != null) { |
| postData.put("username", user.getUsername()); |
| postData.put("avatarUrl", user.getAvatarUrl()); // 改成 avatarUrl,保持驼峰 |
| } else { |
| postData.put("username", "未知用户"); |
| postData.put("avatarUrl", null); |
| } |
| |
| postData.put("postContent", post.getPostContent()); |
| postData.put("imgUrl", post.getImageUrl()); // 改成 imgUrl,和列表接口保持一致 |
| postData.put("postTime", post.getPostTime()); |
| postData.put("postLikeNum", post.getPostLikeNum()); |
| postData.put("postCollectNum", post.getPostCollectNum()); |
| postData.put("title", post.getTitle()); |
| |
| return postData; |
| } else { |
| throw new RuntimeException("Post not found with id: " + postId); |
| } |
| } |
| |
| |
| // 收藏帖子 - 添加 @Transactional |
| @Transactional |
| public void collectPost(Long postId, Long userId) { |
| Post post = postRepository.findById(postId).orElseThrow(() -> new RuntimeException("Post not found")); |
| post.setPostCollectNum(post.getPostCollectNum() + 1); |
| postRepository.save(post); |
| |
| // 添加到收藏表 |
| Collections collection = new Collections(); |
| collection.setUserId(userId); |
| collection.setPostNo(postId); |
| collectionsRepository.save(collection); |
| } |
| |
| // 取消收藏 - 添加 @Transactional |
| @Transactional |
| public void uncollectPost(Long postId, Long userId) { |
| Post post = postRepository.findById(postId).orElseThrow(() -> new RuntimeException("Post not found")); |
| // 减少帖子收藏数 |
| if (post.getPostCollectNum() > 0) { |
| post.setPostCollectNum(post.getPostCollectNum() - 1); |
| postRepository.save(post); |
| } |
| |
| // 从收藏表中删除对应记录 |
| collectionsRepository.deleteLikeByUserIdAndPostNo(userId, postId); |
| } |
| // 获取用户收藏的所有帖子 |
| public List<Map<String, Object>> getAllCollections(Long userId) { |
| // 获取用户收藏的帖子ID |
| List<Collections> collections = collectionsRepository.findByUserId(userId); |
| |
| // 如果没有收藏的帖子,返回空列表 |
| if (collections.isEmpty()) { |
| return new ArrayList<>(); |
| } |
| |
| List<Map<String, Object>> response = new ArrayList<>(); |
| for (Collections collection : collections) { |
| // 根据 postNo 查询帖子 |
| Optional<Post> postOptional = postRepository.findById(collection.getPostNo()); |
| if (postOptional.isPresent()) { |
| Post post = postOptional.get(); |
| |
| // 获取帖子作者的信息 |
| Optional<Users> userOptional = userRepository.findById(post.getUser_id()); |
| if (userOptional.isPresent()) { |
| Users user = userOptional.get(); |
| |
| // 将帖子数据和用户信息封装到 Map 中 |
| Map<String, Object> postInfo = new LinkedHashMap<>(); |
| postInfo.put("postNo", post.getPostNo()); |
| postInfo.put("title", post.getTitle()); |
| postInfo.put("postContent", post.getPostContent()); |
| postInfo.put("imageUrl", post.getImageUrl()); |
| postInfo.put("userId", post.getUser_id()); |
| postInfo.put("username", user.getUsername()); // 帖子作者用户名 |
| postInfo.put("avatarUrl", user.getAvatarUrl()); // 帖子作者头像 |
| |
| response.add(postInfo); |
| } |
| } |
| } |
| return response; |
| } |
| } |