简体   繁体   English

Java JPA过滤器

[英]Java JPA filter

I need to do some checks before execute @Modifying queries like update, insert, delete. 在执行@Modifying查询(如更新,插入,删除)之前,我需要做一些检查。 There is any way to do it at Repository level? 有什么办法可以在存储库级别执行此操作? (Maybe with an annotation). (也许带有注释)。 What I'm looking for is a filter that has to be executed every time a query is performed and decide if the query has to be executed or not for all my repository files. 我正在寻找的是每次执行查询时都必须执行的过滤器,并决定是否必须对我的所有存储库文件执行查询。

Thank you 谢谢

You can use AspectJ to intercept method calls on JPA repositories. 您可以使用AspectJ截获JPA存储库上的方法调用。

Step 1 : Declare your JPA repositories as usual. 步骤1 :照常声明您的JPA存储库。

Step 2 : Optionally annotate repository methods of interest. 步骤2 :可选地注释感兴趣的存储库方法。

Step 3 : Declare an aspect to intercept method calls of interest on JPA repositories. 步骤3 :声明一个方面,以拦截JPA存储库中感兴趣的方法调用。 See this Aspect from my sample application as an example. 请从我的示例应用程序中看到此方面作为示例。

Step 4 : Enable runtime interception in the Spring configuration. 步骤4 :在Spring配置中启用运行时拦截。 See the XML Spring configuration file from the same sample application as an example. 作为示例,请参见同一示例应用程序中的XML Spring配置文件

This is the snippet of code to check if the @Modifying annotation is present and interrupt the execution with an Exception: 这是检查@Modifying注释是否存在并使用Exception中断执行的代码段:

@Component
@Aspect
public class InterceptModify {

    @Before("execution(* org.example.repository.*.*(..))")
    public void intercept(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Annotation[] annotations = signature.getMethod().getAnnotations();

        for (Annotation annotation : annotations) {
            if (annotation.annotationType().equals(Modifying.class)) {
                throw new RuntimeException();
            }
        }
    }}

also remeber to enable aspectJ with the annotation @EnableAspectJAutoProxy in one of your conf class 还记得在您的conf类之一中使用注释@EnableAspectJAutoProxy启用AspectJ

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM