bug_fix+historyview
Change-Id: I6f446c1b660a4322865cfcf5502c88cb772ca0a1
diff --git a/src/main/java/com/example/g8backend/service/IPostService.java b/src/main/java/com/example/g8backend/service/IPostService.java
index 82c792e..a349b59 100644
--- a/src/main/java/com/example/g8backend/service/IPostService.java
+++ b/src/main/java/com/example/g8backend/service/IPostService.java
@@ -2,6 +2,7 @@
import com.example.g8backend.entity.Post;
import com.baomidou.mybatisplus.extension.service.IService;
+import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@@ -16,4 +17,7 @@
void unlikePost(Long userId, Long postId);
List<Post> searchPosts(String keyword, List<Long> tagIds, String author); // 更新为支持多个标签
+
+ @Transactional
+ void recordViewHistory(Long userId, Long postId);
}
diff --git a/src/main/java/com/example/g8backend/service/impl/PostServiceImpl.java b/src/main/java/com/example/g8backend/service/impl/PostServiceImpl.java
index 647095d..f2bef5f 100644
--- a/src/main/java/com/example/g8backend/service/impl/PostServiceImpl.java
+++ b/src/main/java/com/example/g8backend/service/impl/PostServiceImpl.java
@@ -5,11 +5,15 @@
import com.example.g8backend.entity.Post;
import com.example.g8backend.entity.PostLike;
import com.example.g8backend.entity.PostTag;
+import com.example.g8backend.entity.PostView;
import com.example.g8backend.mapper.PostMapper;
+import com.example.g8backend.mapper.PostViewMapper;
import com.example.g8backend.service.IPostService;
import com.example.g8backend.service.IPostTagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
import java.sql.Timestamp;
import java.util.List;
@@ -18,11 +22,14 @@
private final PostMapper postMapper;
+ private final PostViewMapper postViewMapper;
+
@Autowired
private IPostTagService postTagService;
- public PostServiceImpl(PostMapper postMapper) {
+ public PostServiceImpl(PostMapper postMapper, PostViewMapper postViewMapper) {
this.postMapper = postMapper;
+ this.postViewMapper = postViewMapper;
this.baseMapper = postMapper; // 重要:设置 baseMapper
}
@@ -87,4 +94,20 @@
public List<Post> searchPosts(String keyword, List<Long> tagIds, String author) {
return postMapper.searchPosts(keyword, tagIds, author); // 调用mapper的搜索方法
}
+
+
+ @Override
+ @Transactional
+ public void recordViewHistory(Long userId, Long postId) {
+ // 1. 插入浏览记录
+ PostView view = new PostView()
+ .setUserId(userId)
+ .setPostId(postId)
+ .setViewTime(new Timestamp(System.currentTimeMillis()).toLocalDateTime());
+ postViewMapper.insert(view);
+
+ // 2. 原子更新浏览数
+ postMapper.incrementViewCount(postId); // 直接调用原子操作
+ }
+
}
\ No newline at end of file