Validate minimum length of parameter in Spring Jpa Query

Ben Green :

We have a data object Foo that has a string property Bar, and a jpa repository with a method to find Foo by Bar:

@Entity
@Table(name = "FOO")
public class Foo {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "BAR", length = 16, nullable = false)
    private String bar;

    public String getBar() {
        return bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }
}


public interface FooJpaRepository extends JpaRepository<Foo, Long> {

    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    List<Foo> findByBar(String bar);
}

This query is used in multiple places.

We are now looking to hash the value of bar before saving to the database, which is increasing the length of the field. I am going to add a @PrePersist method to the Foo class to check the length of bar before saving it. However, I also want to check the length of the bar parameter in the findByBar method so that when this is used elsewhere, other developers will be alerted to the fact that they are using the unhashed value instead of the hashed value.

Is this possible without creating an implementation of the JpaRepository?

Simon Martinelli :

If you are using Spring Boot you can use Validation:

https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-validation

First annotate the repo with @Validate and then use any Bean Validation Annotation on the method parameters.

For example:

@Validate
public interface FooJpaRepository extends JpaRepository<Foo, Long> {

    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    List<Foo> findByBar(@Size(max = 16) String bar);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=147964&siteId=1