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

使用Hibernate验证创建组验证的步骤,hibernate,validation,jakarta-ee,bean-validation,Hibernate,Validation,Jakarta Ee,Bean Validation,我不太理解使用Hibernate创建组验证的步骤。请任何人帮忙。我有两个来自数据库的类,其中两个类中的一些字段应分组并验证,使用官方hibernate文档,我将采取以下步骤: 假设我有两个带有字段的类: public class Tickets implements Serializable { @NotNull(groups=GroupLotsAndTicketsValidation.class) @Size(groups = GroupLotsAndTicketsVa

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

    public class Tickets implements Serializable {
    @NotNull(groups=GroupLotsAndTicketsValidation.class)
    @Size(groups = GroupLotsAndTicketsValidation.class)
    @NotBlank
    private string Amount;
    //and other fields..
    //getters and setters
    }
这是我的第一节课。以下是第二点:

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级别上使用marker

比如说。您有实体
配置文件

在RESTAPI中,需要进行
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键,则此情况对创建操作有效)。因此,在验证逻辑中,它不应该是
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
):

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

我也希望你已经红了:

  • )
  • )

您的问题似乎重复。第一个回答是@Sergii,谢谢链接,但我需要确切的步骤,我应该创建什么?如果我要创建接口类,我应该向接口类添加什么。谢谢你的理解。注意:在链接中,这家伙没有显示他从哪里得到了类GroupOne.class和GroupTwo.ClassI正在添加
@Validated
注释,但不起作用。@LinuRadu如果需要我帮助,请在这里添加关于您问题的链接(我需要所有详细信息)。在如此抽象的情况下,我无能为力。你知道:抽象的问题得到抽象的答案。
  @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.
  }