通过使用 Jooq 和 JPA 的 @Column 注释验证字段长度

Validating field length by making use of Jooq and JPA's @Column annotation

我正在尝试通过使用 JSR 303 验证来验证用户输入的数据。我尝试实施的一项验证是检查每个字段的输入值大小是否不超过相应列的最大大小。

为了将字段映射到数据库列,我使用了 JPA 的 @Column 注释,如下所示:

@ComplexValidation
public class Person {

    @Column(table = "PERSON_DETAILS", name = "FIRST_NAME")
    private String firstName;

}

Person class 上的 @ComplexValidation 注释是我正在尝试实现的 JSR 303 自定义约束验证器,它基本上尝试执行以下步骤:

  1. 检索 class 中用 @Column 注释
  2. 注释的所有字段
  3. 它从注释中提取 table 名称,并使用它来加载相应的 JOOQ 生成的 class 代表 table
  4. 它从注释中提取字段名称,并使用它来加载相应列的数据类型和大小

在 Jooq 中有什么方法可以根据 table 名称检索 Jooq 生成的 class 吗?我的第一次尝试可以在下面找到,但是它不起作用,因为 table(tableName) returns SQLTable 而不是 TableImpl 对象:

Column columnAnnotation = field.getDeclaredAnnotation(Column.class);
if (columnAnnotation != null) {
    String tableName = columnAnnotation.table();
    String fieldName = columnAnnotation.name();

    TableField tableField = (TableField) ((TableImpl) table(tableName)).field(fieldName);
    int columnLength = tableField.getDataType().length();

    if (fieldValue.length() > columnLength) {
        constraintValidatorContext
            .buildConstraintViolationWithTemplate("exceeded maximum length")
            .addPropertyNode(field.getName())
            .addConstraintViolation();
    }
}

欢迎任何其他建议:)

假设您只有一个生成的模式(例如 PUBLIC),您可以从那里访问表:

Table<?> table = PUBLIC.getTable(tableName);

Schema.getTable(String)