有没有办法为Spring数据存储库定义允许过滤数据的通用过滤器,类似于Hibernate可用的?举个例子,如果我可以做这样的话会很酷:
@FilterDef(name = "clientSecurity", defaultCondition = "clientId in (:allowableClients)", parameters = { @ParamDef(name = "allowableClients", type = "Long") })
public interface DocumentRepository extends Repository<Document, Long> {
public List<Document> findAll();
}
Run Code Online (Sandbox Code Playgroud)
因此,在上面的示例中,我的文档存储库只返回允许客户端ID集合中属于客户端的所有文档.
我通过使用自定义存储库来实现这一点.据我所知,没有一种直截了当的方式.以下是我在Comment下面给出的实体上所做的.
@Entity
@FilterDef(name="filterByEmail", parameters={@ParamDef(name="email", type="string")})
@Filters( {
@Filter(name="filterByEmail", condition=":email = email")
} )
public class Comment {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String firstname;
private String lastname;
private String email;
}
Run Code Online (Sandbox Code Playgroud)
如下定义存储库
@Repository
@Transactional
public interface CommentRepository extends CrudRepository<Comment, Long>,CommentRepositoryCustom {
}
Run Code Online (Sandbox Code Playgroud)
在自定义存储库中获取EntityManager和启用会话的句柄.
public class CommentRepositoryImpl implements CommentRepositoryCustom{
@PersistenceContext
private EntityManager entityManager;
@Autowired
private CommentRepository commentRepository;
@Override
public Iterable<Comment> findCommentWithEmail(String email) {
Filter filter = (Filter)entityManager.unwrap(Session.class).enableFilter("filterByEmail");
filter.setParameter("email", "arun.menon");
Iterable<Comment> iterable = commentRepository.findAll();
entityManager.unwrap(Session.class).disableFilter("filterByEmail");
return iterable;
}
}
Run Code Online (Sandbox Code Playgroud)
以下是测试执行.
public void run(String... arg0) throws Exception {
Iterable<Comment> iterable = commentService.findCommentWithEmail("test@test.com");
System.out.println("User ois" + iterable);
}
Run Code Online (Sandbox Code Playgroud)
如果您需要更通用的解决方案,请参阅此处.
| 归档时间: |
|
| 查看次数: |
14453 次 |
| 最近记录: |