magemello
magemello

Reputation: 1202

Java JPA filter

I need to do some checks before execute @Modifying queries like update, insert, delete. 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

Upvotes: 0

Views: 294

Answers (2)

manish
manish

Reputation: 20135

You can use AspectJ to intercept method calls on JPA repositories.

Step 1: Declare your JPA repositories as usual.

Step 2: Optionally annotate repository methods of interest.

Step 3: Declare an aspect to intercept method calls of interest on JPA repositories. See this Aspect from my sample application as an example.

Step 4: Enable runtime interception in the Spring configuration. See the XML Spring configuration file from the same sample application as an example.

Upvotes: 1

magemello
magemello

Reputation: 1202

This is the snippet of code to check if the @Modifying annotation is present and interrupt the execution with an 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

Upvotes: 0

Related Questions