Java JPA 过滤器
Java JPA filter
我需要在执行更新、插入、删除等@Modifying 查询之前进行一些检查。
有什么办法可以在存储库级别做到这一点? (也许带有注释)。
我正在寻找的是每次执行查询时都必须执行的过滤器,并决定是否必须对我的所有存储库文件执行查询。
谢谢
您可以使用 AspectJ 拦截对 JPA 存储库的方法调用。
第 1 步:照常声明您的 JPA 存储库。
步骤 2:可选择注释感兴趣的存储库方法。
第 3 步:声明一个方面以拦截 JPA 存储库中感兴趣的方法调用。请参阅我的示例应用程序中的 this Aspect 作为示例。
第四步:在Spring配置中启用运行时拦截。请参阅来自同一示例应用程序的 the XML Spring configuration file 作为示例。
这是检查@Modifying 注释是否存在并用异常中断执行的代码片段:
@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();
}
}
}}
还记得在您的其中一个 conf class
中使用注释 @EnableAspectJAutoProxy 启用 aspectJ
我需要在执行更新、插入、删除等@Modifying 查询之前进行一些检查。 有什么办法可以在存储库级别做到这一点? (也许带有注释)。 我正在寻找的是每次执行查询时都必须执行的过滤器,并决定是否必须对我的所有存储库文件执行查询。
谢谢
您可以使用 AspectJ 拦截对 JPA 存储库的方法调用。
第 1 步:照常声明您的 JPA 存储库。
步骤 2:可选择注释感兴趣的存储库方法。
第 3 步:声明一个方面以拦截 JPA 存储库中感兴趣的方法调用。请参阅我的示例应用程序中的 this Aspect 作为示例。
第四步:在Spring配置中启用运行时拦截。请参阅来自同一示例应用程序的 the XML Spring configuration file 作为示例。
这是检查@Modifying 注释是否存在并用异常中断执行的代码片段:
@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();
}
}
}}
还记得在您的其中一个 conf class
中使用注释 @EnableAspectJAutoProxy 启用 aspectJ