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

时间:2017-07-10 04:13:53

标签: hibernate validation java-ee bean-validation

我真的不了解使用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...
    }

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

1 个答案:

答案 0 :(得分:2)

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

例如。您有实体Profile

在您的rest 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 nonNull约束异常。您在创建操作中不需要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.
  }

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

我也希望你已经红了: