java点赞_java实现点赞功能示例
时间: 2023-07-12 09:53:19 浏览: 140
Java实现点赞功能的示例:
1. 创建一个点赞表,包含用户ID和被点赞的ID。
```
CREATE TABLE `like_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL COMMENT '用户ID',
`liked_id` int(11) NOT NULL COMMENT '被点赞的ID',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `idx_user_id` (`user_id`),
KEY `idx_liked_id` (`liked_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='点赞表';
```
2. 创建点赞服务,提供点赞和取消点赞的接口。
```
@Service
public class LikeService {
private final LikeMapper likeMapper;
@Autowired
public LikeService(LikeMapper likeMapper) {
this.likeMapper = likeMapper;
}
/**
* 点赞
*
* @param userId 用户ID
* @param likedId 被点赞的ID
*/
public void like(int userId, int likedId) {
Like like = new Like();
like.setUserId(userId);
like.setLikedId(likedId);
likeMapper.insert(like);
}
/**
* 取消点赞
*
* @param userId 用户ID
* @param likedId 被点赞的ID
*/
public void unlike(int userId, int likedId) {
LikeExample example = new LikeExample();
example.createCriteria()
.andUserIdEqualTo(userId)
.andLikedIdEqualTo(likedId);
likeMapper.deleteByExample(example);
}
}
```
3. 创建点赞控制器,处理点赞和取消点赞的请求。
```
@RestController
@RequestMapping("/like")
public class LikeController {
private final LikeService likeService;
@Autowired
public LikeController(LikeService likeService) {
this.likeService = likeService;
}
/**
* 点赞
*
* @param userId 用户ID
* @param likedId 被点赞的ID
* @return
*/
@PostMapping("/like")
public ResultVO like(@RequestParam("userId") int userId,
@RequestParam("likedId") int likedId) {
likeService.like(userId, likedId);
return ResultVO.success();
}
/**
* 取消点赞
*
* @param userId 用户ID
* @param likedId 被点赞的ID
* @return
*/
@PostMapping("/unlike")
public ResultVO unlike(@RequestParam("userId") int userId,
@RequestParam("likedId") int likedId) {
likeService.unlike(userId, likedId);
return ResultVO.success();
}
}
```
阅读全文