Spring data jpa - modifying query before execution

北战南征 提交于 2021-02-18 07:37:04

问题


I'm working on a project that keeps some access control information in the database. We're using that access control information to filter what the user can see. The filter that we're using is based on roles that the user has. We would like to use the Repository abstraction provided by Spring Data, but we would like to be able to adjust the generated queries before they are executed. Is there a way to attach a listener or an interceptor that will be called before a query is executed? That way we can get a reference to the query object and make whatever adjustments to the query we need to before the query is executed.

What we're thinking about doing is creating our own JpaRepositoryFactoryBean so we can override SimpleJpaRepository as described here. We would override SimpleJpaRepository.getQuery to make adjustments to the query. Then for all the generated finder methods we were thinking about extending PartTreeJpaQuery and overriding the PartTreeJpaQuery$QueryPreparer. In the QueryPreparer we would override QueryPreparer.createQuery methods. We weren't sure if that was the simplest way to get access to all queries before they get executed.

We thought about adding a org.springframework.data.repository.core.support.QueryCreationListener, but it would only get executed when the query is created. I think we need something more dynamic.


回答1:


I'm not sure if you already know, but Spring Data team is working on that feature for the next release, to make it possible for Spring Security Team to add the support for ACLs then.

Add infrastructure for generic query augmentation

Spring Security issue that is blocked by the previous: Spring Security / Spring Data Acl Integration

In my company, we created a JpaRepositoryFactoryBean that would create a custom Repository to allow us to add the filter for the ACLs, but we just did that for the findAll and findOne methods, so we were loosing a lot of features of Spring Data and decided to revert that change and we're still thinking in a way to do it automatically. If we find out that it'll be too difficult, I think that we'll delegate that responsibility on the clients of the repositories and wait for the support for it in Spring Security/Data.

The original question already has 1 year. Did you find a clean way to do it?



来源:https://stackoverflow.com/questions/22712163/spring-data-jpa-modifying-query-before-execution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!