Spring Data + JPA的过滤器 [英] Filters For Spring Data + JPA

查看:816
本文介绍了Spring Data + JPA的过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方法可以为Spring数据存储库定义通用过滤器,从而允许过滤出数据(类似于Hibernate可用的过滤器)?举个例子,如果我可以做这样的事情,那将很酷:

Is there any way to define generic filters for Spring data repositories that allow filtering out data, similar to what is available with Hibernate? As an example it would be cool if I could do something like this:

@FilterDef(name = "clientSecurity", defaultCondition = "clientId in (:allowableClients)", parameters = { @ParamDef(name = "allowableClients", type = "Long") })
public interface DocumentRepository extends Repository<Document, Long> {
    public List<Document> findAll();
}

因此在上面的示例中,我的文档存储库将只返回允许的客户端ID集中属于客户端的所有文档.

So in the above example, my document repository would only return all documents that belong to client in the set of allowable client ids.

推荐答案

我通过使用自定义存储库使此工作正常进行.据我所知,这是您所期望的那种简单的方法.以下是我对下面给出的Comment实体所做的操作.

I got this working by using custom repository. There is no straightforward way the kind you are expecting as far as I know. Following is what I did on a Comment entity given below.

@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;
}

定义存储库如下

@Repository
@Transactional
public interface CommentRepository extends CrudRepository<Comment, Long>,CommentRepositoryCustom {
}

在自定义存储库中,获取EntityManager的句柄并启用会话.

In the custom repository get a handle on the EntityManager and enable session.

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;
    }

}

以下是执行的测试.

public void run(String... arg0) throws Exception {
    Iterable<Comment> iterable = commentService.findCommentWithEmail("test@test.com");
    System.out.println("User ois" + iterable);
}

如果您需要更通用的解决方案,请参考这里.

If you need a more generic kind of solution refer here.

这篇关于Spring Data + JPA的过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆