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

查看:32
本文介绍了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

Defined a Repository as follows

@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天全站免登陆