显示用户有权访问的N个项目

时间:2013-12-16 06:50:42

标签: java spring spring-security spring-data

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

DAO:

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项,但我想知道是否有更优雅的方法来做到这一点。

1 个答案:

答案 0 :(得分:1)

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

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

假设对新闻的查询返回速度很快,那么查询25或X结果将不会那么多,以至于没有达到用户的最终5的机会足够低并且你生活的结果是没有达到5在某些情况下:)

相关问题