使用 Hibernate 验证创建组验证的步骤

Steps for creating Group Validation Using Hibernate Validation

我不太了解使用 Hibernate 创建组验证的步骤。请任何人帮忙。我有两个来自数据库的 classes,其中来自两个 classes 的一些字段应该被分组和验证,使用官方休眠文档我采取后续步骤: 假设我有两个 classes 字段:

    public class Tickets implements Serializable {
    @NotNull(groups=GroupLotsAndTicketsValidation.class)
    @Size(groups = GroupLotsAndTicketsValidation.class)
    @NotBlank
    private string Amount;
    //and other fields..
    //getters and setters
    }

这是我的第一个 class。这是第二个:

public class Lots implements Serializable {

@NotNull(groups = GroupLotsAndTicketsValidation.class)
@Size(groups = GroupLotsAndTicketsValidation.class)
@NotBlank(groups =GroupLotsAndTicketsValidation.class)
private String title;
@NotNull(groups = GroupLotsAndTicketsValidation.class)
@NotBlank(groups =GroupLotsAndTicketsValidation.class)
private String fullWeight;
//and other fields..
//getters and setters...
    }

这是我的第二个 class。 我还读到我应该为每个 class 创建一个接口。但是,我认为如果我想创建自己的注释就应该这样做。 我是否应该创建接口以及接下来要采取什么步骤。提前致谢

群接口未实现。这是验证的标志。您可以在测试中使用此标记。如果您使用像 spring 这样强大的框架,您可以在 @Controller 或任何 bean 级别上使用标记。

例如。您有实体 Profile

在您的休息 API 中,您需要进行 POST(创建)和 PUT(更新)操作。所以你会有

@RestController
public class ProfileController {
  @PostMapping("/profile")
  public Calendar insert(@RequestBody @Valid Profile profile) {
    return null; // implement me
  }
  @PutMapping("/profile/{profileId}/")
  public void update(@PathVariable String profileId, @RequestBody @Valid Profile profile) {
    // todo implement me.
  }
}

在使用任何更新操作之前,您必须在实体中输入 id 值(仅作为示例,如果在 java 端管理 id-key,则这种情况对创建操作有效)。所以它不应该是 null 在你的验证逻辑中。

public class Profile {
  @Id
  @NotNull
  private Long id;
  private String name;
  @NotNull
  private String email;
}

如果您尝试使用它,您将在创建操作中得到 ui 非空约束异常。在创建操作中不需要 ID notNull 验证,但在更新操作中需要验证!解决方案之一是创建具有自己验证的不同 dto 对象,其他 - 从 id 字段中删除验证,替代解决方案是使用:

public class Profile {
  @Id
  @NotNull(groups = UpdateOperation.class)
  private Long id;
  private String name;
  @NotNull
  private String email;
}

public interface UpdateOperation {}

并将更改添加到控制器中(@Valid (JSR-303) 应该迁移到支持验证组 spring 提供 @Validated 的验证器注解:

  @PostMapping("/profile")
  public Calendar insert(@RequestBody @Validated Profile profile) {
    return null; // implement me
  }
  @PutMapping("/profile/{profileId}/")
  public void update(@PathVariable String profileId, @RequestBody @Validated({UpdateOperation.class}) Profile profile) {
    // todo implement me.
  }

因此,您不需要为每个 rest 操作创建 dto,并且您可以在 rest 级别上进行灵活的验证。

也希望你已经红了: