Java Stream检查列表对象是否存在:关注系统防重复校验失效问题
问题原因及修复方案
你现有代码存在2个核心逻辑错误导致校验不生效:
- 过滤条件写反了:Followers实体中
from字段对应发起关注的用户,to字段对应被关注的用户。你从被关注用户的粉丝列表中查询时,应该匹配每条记录的from.id是否等于当前登录用户id,而非to.id - 校验判断对象错误:你现在判断的是被关注用户的粉丝列表总长度是否大于0,只要对方有1个粉丝就会直接禁止关注,完全没有用到你前面过滤后的结果
修复后的业务代码
public ResponseEntity<?> followUser(String username, User user) { // 要被关注的目标用户 User targetUser = getByUsername(username); // 新增前置校验:不允许自己关注自己 if (targetUser.getId().equals(user.getId())) { return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Cannot follow yourself"); } // 校验是否已经关注:判断目标用户的粉丝列表中是否存在发起方为当前用户的记录 boolean hasFollowed = targetUser.getFollowers().stream() .anyMatch(followRecord -> followRecord.getFrom().getId().equals(user.getId())); if (hasFollowed) { return ResponseEntity.status(HttpStatus.FORBIDDEN).body("You have already followed this user"); } // 保存关注记录 Followers followers = new Followers(); followers.setFrom(user); followers.setTo(targetUser); followersRepository.save(followers); return ResponseEntity.ok(new GenericResponse("Followed")); }
额外优化建议
- 数据库层面加唯一约束:在Followers表的
from_user_fk和to_user_fk两个字段上添加联合唯一索引,避免并发请求下业务校验没拦住导致的重复数据,直接在实体类上加注解即可:
@Entity @Table(uniqueConstraints = { @UniqueConstraint(columnNames = {"from_user_fk", "to_user_fk"}) }) public class Followers { // 原有代码保持不变 }
- 大流量场景性能优化:不用加载整个粉丝列表再过滤,直接在Repository层新增查询方法判断是否存在记录,性能更高:
// FollowersRepository中新增方法 boolean existsByFromIdAndToId(Long fromUserId, Long toUserId);
业务层直接调用该方法判断即可,无需查询全量粉丝数据。
内容的提问来源于stack exchange,提问作者onur
相关产品推荐
相关产品推荐

