本文介绍了jOOQ:允许的字符约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑从Hibernate迁移到jOOQ,但找不到在Hibernate中如何在String上具有模式约束:

I am considering moving from Hibernate to jOOQ but I can't find e.g.how to have Pattern-Constraints on a String like this in Hibernate:

@NotEmpty(message = "Firstname cannot be empty")
@Pattern(regexp = "^[a-zA-Z0-9_]*$", message = "First Name can only contain characters.")
private String firstname;

我将如何在jOOQ中做到这一点?

How would I do that in jOOQ?

推荐答案

"jOOQ方式"

进行此类验证的"jOOQ方法"将是创建以下任一方法:

The "jOOQ way"

The "jOOQ way" to do such validation would be to create either:

  • 数据库中的CHECK约束.
  • 数据库中的触发器.
  • 数据库中的域.
  • A CHECK constraint in the database.
  • A trigger in the database.
  • A domain in the database.

毕竟,如果您要确保数据完整性,那么数据库就是此类约束和完整性检查的来源(可能除了功能上等效的客户端验证之外).想象一下一个批处理作业,一个Perl脚本,甚至是一个绕过JSR-303验证的JDBC语句.您会立即发现数据损坏.

After all, if you want to ensure data integrity, the database is where such constraints and integrity checks belong (possibly in addition to functionally equivalent client-side validation). Imagine a batch job, a Perl script, or even a JDBC statement that bypasses JSR-303 validation. You'll find yourself with corrupt data in no time.

如果确实要实现客户端验证,则仍可以在DTO上使用JSR-303,例如,DTO与UI交互.但是您必须 在将数据传递到jOOQ进行存储之前进行验证(如artbristol所述 ).

If you do want to implement client-side validation, you can still use JSR-303 on your DTOs, which interact with your UI, for instance. But you will have to perform validation before passing the data to jOOQ for storage (as artbristol explained).

但是,您可以通过在各个列上声明Converter并通过将这样的Converter注册到源代码生成器中.

You could, however, use your own custom type by declaring a Converter on individual columns and by registering such Converter with the source code generator.

本质上,Converter是:

public interface Converter<T, U> extends Serializable {
    U from(T databaseObject);
    T to(U userObject);
    Class<T> fromType();
    Class<U> toType();
}

在您的情况下,您可以这样实现注释:

In your case, you could implement your annotations as such:

public class NotEmptyAlphaNumericValidator implements Converter<String, String> {

    // Validation
    public String to(String userObject) {
        assertNotEmpty(userObject);
        assertMatches(userObject, "^[a-zA-Z0-9_]*$");
        return userObject;
    }

    // Boilerplate
    public String from(String databaseObject) { return databaseObject; }
    public Class<String> fromType() { return String.class; }
    public Class<String> toType() { return String.class; }
}

请注意,这更像是一种变通方法,因为Converter尚未针对该用例进行设计,即使它可以完美地实现.

Note that this is more of a workaround, as Converter hasn't been designed for this use-case, even if it can perfectly implement it.

还有一个待处理的功能请求#4543 为客户端提供更多支持,侧面验证.从jOOQ 3.7开始,此功能尚未实现.

There's also a pending feature request #4543 to add more support for client-side validation. As of jOOQ 3.7, this is not yet implemented.

这篇关于jOOQ:允许的字符约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 05:11