【问题标题】:Display N items that user has access to显示用户有权访问的 N 个项目
【发布时间】:2014-01-03 11:53:55
【问题描述】:

使用 Spring Data 1.4.2 和 Sprint Security 3.1.4.RELEASE。

道:

public interface NewsDao extends 
    JpaRepository<News, Long>, JpaSpecificationExecutor<News>{}

我想获取用户可以访问的 5 条最新消息:

@Transactional(readOnly = true)
@PostFilter("hasPermission(filterObject, 'VIEW')")
public List<News> findNewestGlobalNews() {
    Sort orderByDate = getSort();
    NewsDao newsDao = getDao();
    PageRequest newestOnly = new PageRequest(0, 5, orderByDate);
    List<News> news = newsDao.findAll(newestOnly).getContent();
    // because the list returned by Page is immutable and we do the filtering
    // according to ACL, return a copy of the list
    return new ArrayList<>(news);
}

此代码有效,但存在明显问题:我们从数据库中选择 5 个项目,然后过滤掉用户无权访问的项目。这会导致一个用户看到 3 个新闻,而另一个用户看到 4 个,尽管数据库中至少有 5 个新闻两个用户都可能看到。

我可以考虑从数据库中选择所有项目,然后将它们过滤掉并选择前 5 个,但我想知道是否有更优雅的方法来做到这一点。

【问题讨论】:

    标签: java spring spring-security spring-data


    【解决方案1】:

    干净的解决方案是直接查询特定用户的最后 5 个。这显然只有当您在数据库中也有此信息时才有效。

    如果您仅在服务层中拥有此访问信息,则在第一次查询后列表小于 5 时,您需要进行更多查询,直到总共达到 5。

    假设新闻查询返回很快,那么查询 25 或 X 个结果就不会那么麻烦了,这样用户没有达到最后 5 个结果的机会就足够低了,而你忍受着没有达到 5 个结果的后果在某些情况下:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-30
      • 2020-02-20
      • 2020-04-22
      • 2020-01-16
      相关资源
      最近更新 更多