使用 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 个,但我想知道是否有更优雅的方法来做到这一点。
最佳答案
干净的解决方案是直接查询特定用户的最后 5 个。显然,只有当数据库中也有此信息时,这才有效。
如果您仅在服务层中拥有此访问信息,则如果在第一次查询后列表小于 5,则您只能查询更多,直到总数达到 5。
假设新闻查询返回速度很快,那么查询 25 或 X 个结果并不那么重要,因此用户未达到最后 5 个结果的可能性足够低,并且在某些情况下您会面临未达到 5 个结果的后果:)
关于java - 显示用户有权访问的 N 个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20605025/