Springboot微信小程序收藏功能代码
时间: 2024-03-15 11:18:31 浏览: 12
可以回答这个问题。以下是一个简单的实现收藏功能的 Spring Boot 微信小程序代码示例:
1. 创建一个收藏实体类
```java
@Entity
@Table(name = "collection")
public class Collection {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long userId;
private Long articleId;
public Collection() {
}
public Collection(Long userId, Long articleId) {
this.userId = userId;
this.articleId = articleId;
}
// getters and setters
}
```
2. 创建一个收藏服务类
```java
@Service
public class CollectionService {
@Autowired
private CollectionRepository collectionRepository;
public boolean isCollected(Long userId, Long articleId) {
Collection collection = collectionRepository.findByUserIdAndArticleId(userId, articleId);
return collection != null;
}
public void collect(Long userId, Long articleId) {
if (!isCollected(userId, articleId)) {
Collection collection = new Collection(userId, articleId);
collectionRepository.save(collection);
}
}
public void cancelCollect(Long userId, Long articleId) {
Collection collection = collectionRepository.findByUserIdAndArticleId(userId, articleId);
if (collection != null) {
collectionRepository.delete(collection);
}
}
}
```
3. 创建一个收藏控制器类
```java
@RestController
@RequestMapping("/api/collection")
public class CollectionController {
@Autowired
private CollectionService collectionService;
@PostMapping("/collect")
public void collect(@RequestParam("userId") Long userId,
@RequestParam("articleId") Long articleId) {
collectionService.collect(userId, articleId);
}
@PostMapping("/cancelCollect")
public void cancelCollect(@RequestParam("userId") Long userId,
@RequestParam("articleId") Long articleId) {
collectionService.cancelCollect(userId, articleId);
}
@GetMapping("/isCollected")
public boolean isCollected(@RequestParam("userId") Long userId,
@RequestParam("articleId") Long articleId) {
return collectionService.isCollected(userId, articleId);
}
}
```
以上代码仅供参考,实际应用时需要根据具体需求进行修改和完善。