验证Spring Jpa Query中参数的最小长度 [英] Validate minimum length of parameter in Spring Jpa Query

查看:38
本文介绍了验证Spring Jpa Query中参数的最小长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个数据对象 Foo,它有一个字符串属性 Bar,还有一个 jpa 存储库,其中包含一个通过 Bar 查找 Foo 的方法:

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.

我们现在希望在保存到数据库之前对 bar 的值进行散列,这会增加字段的长度.我将在 Foo 类中添加一个 @PrePersist 方法,以在保存之前检查 bar 的长度.但是,我还想检查 findByBar 方法中 bar 参数的长度,以便在其他地方使用它时,其他开发人员将被提醒他们使用的是未散列值而不是散列值.

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.

如果不创建 JpaRepository 的实现,这可能吗?

Is this possible without creating an implementation of the JpaRepository?

推荐答案

如果你使用 Spring Boot 你可以使用验证:

If you are using Spring Boot you can use Validation:

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

首先使用 @Validate 注释 repo,然后在方法参数上使用任何 Bean Validation Annotation.

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

例如:

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

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

这篇关于验证Spring Jpa Query中参数的最小长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆