【问题标题】:JPQL for finding if user has sent or recieved friend request from an other userJPQL 用于查找用户是否已发送或接收来自其他用户的好友请求
【发布时间】:2020-08-30 12:09:24
【问题描述】:

我一直在开发简单的社交网络项目,我是在AppUser.java中实现User -> Friend关系:

@Data
@Entity(name = "users")
@NoArgsConstructor
@RequiredArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class AppUser extends AuditModel {

    @NonNull
    private String userName;

    @NonNull
    @Column(unique = true, nullable = false)
    private String userEmail;

    private String userPassword;

    @OneToMany( mappedBy="owner", cascade=CascadeType.ALL, orphanRemoval = true)
    private List<Friend> friends = new ArrayList<>();

}

和 Friend.java

@Data
@Entity(name = "friends")
@NoArgsConstructor
@RequiredArgsConstructor
@EqualsAndHashCode(exclude = {"owner"}) // to avoid StackOverflow
@ToString(exclude = {"owner"}) // // to avoid StackOverflow
public class Friend{

    @NonNull
    @EmbeddedId
    private Key key = new Key();

    @NonNull
    @ManyToOne
    @MapsId("ownerId")
    private AppUser owner;

    @NonNull
    @ManyToOne
    @MapsId("personId")
    private AppUser person;

    @NonNull
    private boolean accepted;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Embeddable
    public static class Key implements Serializable {
        private Long ownerId;
        private Long personId;
    }
}

如果用户向其他用户发送好友请求,记录如下:

此时一切正常,除了我想在向我发送好友请求或我向他发送好友请求的用户的个人资料页面上隐藏 Add Friend 按钮的情况,我尝试使用 @ FriendRepository.java 中的 987654327@ 为:

@Repository
public interface FriendRepository extends PagingAndSortingRepository<Friend, Long> {

    @Query(value = "SELECT count(f) FROM friends f WHERE (f.owner.id = :id OR f.person.id = :id)")
    Integer findPendingOrFriend(@Param("id") Long id);

}

在服务中我有:

    public boolean findPendingOrFriend(Long id) {
        // Find friends ids who/Whom friend requests are sent
        return friendRepository.findPendingOrFriend(id) > 0;
    }

在控制器中我有:

@GetMapping(value = "/{userId}/profile")
public String showProfile(
        Model model,
        @PathVariable(value = "userId") Long userId
) throws Exception {

    // Send model
    String pageTitle = "User " + Util.getLoggedInUser(userService).getUserFirstName() ;
    model.addAttribute("pageTitle", pageTitle);
    model.addAttribute("loggedInUser", Util.getLoggedInUser(userService));
    model.addAttribute("profileUser", userService.findById(userId).orElseThrow(EntityNotFoundException::new));

    // Check if pending or friend
    boolean isPendingOrFriend = friendService.findPendingOrFriend(userId);
    model.addAttribute("isPendingOrFriend", isPendingOrFriend);
    return "user_profile";
}

但它没有按预期工作,因为它为尚未向应用程序的任何其他用户发送任何好友请求的新用户隐藏了Add Friend 按钮,并且当发送好友请求时它始终显示Add Friend 按钮在用户个人资料页面上。 问题是我怎样才能重写

    @Query(value = "SELECT count(f) FROM friends f WHERE (f.owner.id = :id OR f.person.id = :id)")
    Integer findPendingOrFriend(@Param("id") Long id);

这样它就可以按照上面的要求工作。

【问题讨论】:

  • 发送请求会改变什么,会改变哪个属性?
  • @sc0der 请查看更新。
  • 我发了一篇,希望能成功!

标签: java spring-boot spring-data-jpa jpql


【解决方案1】:

您的查询将不起作用,因为您检查了不正确的所有者 ID 或人员 ID,

您应该同时检查访问者 ID 和所有者页面 ID 的 ID

    @Query(value = "SELECT count(f) FROM friends f WHERE ((f.owner.id = :id1 AND f.person.id = :id2) OR (f.owner.id = :id2 AND f.person.id = :id1))")
    Integer findPendingOrFriend(@Param("id1") Long id1, @Param("id2") Long id2);

【讨论】:

    【解决方案2】:

    请记住我宁愿选择以下方案:

    @Query(value = "SELECT count(f) FROM friends f WHERE (f.owner.id = :oId AND f.person.id = :pId) OR (f.person.id = :oId AND f.owner.id = :pId)")
    Integer findPendingOrFriend(@Param("oId") Long oId, @Param("pId") Long pId);
    

    Service:

    public boolean findPendingOrFriend(Long oId, Long pId) {
         // Find friends ids
         return friendRepository.findPendingOrFriend(oId, pId) > 0;
    }
    

    在控制器中:

    @GetMapping(value = "/{userId}/profile")
        public String showProfile(
                Model model,
                @PathVariable(value = "userId") Long userId
        ) throws Exception {
    
            AppUser loggedInUser = Util.getLoggedInUser(userService);
    
            // Send model
            String pageTitle = "User " + loggedInUser.getUserFirstName() ;
            model.addAttribute("pageTitle", pageTitle);
            model.addAttribute("loggedInUser", loggedInUser);
            model.addAttribute("profileUser", userService.findById(userId).orElseThrow(EntityNotFoundException::new));
    
            // Check if pending or friend
            boolean isPendingOrFriend = friendService.findPendingOrFriend(loggedInUser.getId(), userId);
            model.addAttribute("isPendingOrFriend", isPendingOrFriend);
            return "user_profile";
        }
    

    希望这能按预期工作。

    【讨论】:

      猜你喜欢
      • 2016-04-06
      • 1970-01-01
      • 2014-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多