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

Steps for creating Group Validation Using Hibernate Validation

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

1
2
3
4
5
6
7
8
    public class Tickets implements Serializable {
    @NotNull(groups=GroupLotsAndTicketsValidation.class)
    @Size(groups = GroupLotsAndTicketsValidation.class)
    @NotBlank
    private string Amount;
    //and other fields..
    //getters and setters
    }

这是我的第一堂课。这是第二个:

1
2
3
4
5
6
7
8
9
10
11
12
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...
    }

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


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

例如。你有实体 Profile

在您的其余 API 中,您需要有 POST(创建)和 PUT(更新)操作。所以你将拥有

1
2
3
4
5
6
7
8
9
10
11
@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 值(仅举例,如果 id-key 在 java 端管理,则这种情况对创建操作有效)。所以它不应该是 null 在你的验证逻辑中。

1
2
3
4
5
6
7
8
public class Profile {
  @Id
  @NotNull
  private Long id;
  private String name;
  @NotNull
  private String email;
}

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

1
2
3
4
5
6
7
8
9
10
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):

1
2
3
4
5
6
7
8
  @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级别进行灵活的验证。

也希望你已经红了:

  • 第 2 章逐步验证;
  • 第 5 章分组约束;
  • Spring验证。