How can I do bean-validation with spring repositories?

Viewed 1019

I'm trying to use my repository interface looks like this.

interface SomeRepository extends JpaRepository<Some, Long> {

   @org.springframework.lang.Nullable
   Some findByKey(
            @org.springframework.lang.NonNull
            @javax.validation.constraint.NotNull
            final String key);
}

And I found those constraints don't work as expected.

@Test
void findByKeyWithNullKey() {
    repository.findByKey(null);
}

The test case simply passes.

How can I make it work?

3 Answers

According to Spring JPA document :

To enable runtime checking of nullability constraints for query methods, you need to activate non-nullability on the package level by using Spring’s @NonNullApi.

you can add package annotations simply by creating package-info.java file and add the package declaration that it relates to in the file.Then add this annotation to your package like so :

@org.springframework.lang.NonNullApi
package com.example;

I would suggest to use javax validation in your spring framework and suppose if you are using maven so you just have to include below dependency

<dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </dependency>

after that please try below code

Some findByKey(
            @NotNull final String key);

It works as you pasted the code. Of course, you need to use @Repository on the repo and remove @javax.validation.constraint.NotNull since that's not what you want. Furthermore, you need to make sure you have the proper imports in the pom. I'd recommend doing the reverse, adding non null api on package level, then:

Rule findOneByExpression(@Nullable String expression);
ruleRepository.findOneByExpression(null);

And see it fail, if it returns null. Then change it like so:

@Nullable 
Rule findOneByExpression(@Nullable String expression);

And it will pass.

Related