Validate minimum length of parameter in Spring Jpa Query

不打扰是莪最后的温柔 提交于 2021-01-28 03:51:56

问题


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?


回答1:


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);
}


来源:https://stackoverflow.com/questions/54417388/validate-minimum-length-of-parameter-in-spring-jpa-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!