为了账号安全,请及时绑定邮箱和手机立即绑定

javax验证不验证notNull

javax验证不验证notNull

肥皂起泡泡 2023-09-27 16:48:45
我有一个 springBoot 2.1.9.RELEASE 应用程序,它使用 Spring Data for Couchbase我有这个对象@Data@AllArgsConstructor@NoArgsConstructorpublic class Hostel<T> {    @NotNull    @JsonProperty("_location")    private T location;}还有这个@Document@Data@AllArgsConstructor@NoArgsConstructor@EqualsAndHashCode(of = { "id" })@Builderpublic class HTMDoc {    @Id    private String id;    @NotNull    @Field    private Hostel hostel;}关于服务public HTMDoc create(@Valid HTMDoc doc) {    return repository.save(doc);}在测试中service.create(new HTMDoc());但是当我保存时,我收到了此错误,而不是旅馆字段中的验证 NotNull org.springframework.data.mapping.MappingException: An ID property is needed, but not found/could not be generated on this entity.
查看完整描述

4 回答

?
慕盖茨4494581

TA贡献1850条经验 获得超11个赞

您需要@org.springframework.validation.annotation.Validated在服务类上使用注释来启用验证。


@Validated

@Service

public class DocService {

  public HTMDoc create(@Valid HTMDoc doc) {

    return repository.save(doc);

  }

}


查看完整回答
反对 回复 2023-09-27
?
侃侃无极

TA贡献2051条经验 获得超10个赞

将以下注释添加到 id 中并尝试一下:


@Id

@GeneratedValue(strategy = GenerationStrategy.UNIQUE)

private String id;

有关注释的更多信息@GeneratedValue可以在这个很好的答案中找到:Spring generatedValue注释的用法


查看完整回答
反对 回复 2023-09-27
?
翻翻过去那场雪

TA贡献2065条经验 获得超13个赞

请在您的 id 字段中添加以下语法


@Data

@AllArgsConstructor

@NoArgsConstructor

public class Hostel<T> {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    @Column(name = "id", nullable = false, updatable = false)

    private Long id;


    @NotNull

    @JsonProperty("_location")

    private T location;


}

还可以在服务类中使用 validate 注释。


@Validated

@Service

public class DocService {

  public HTMDoc create(@Valid HTMDoc doc) {

    return repository.save(doc);

  }

}


查看完整回答
反对 回复 2023-09-27
?
ABOUTYOU

TA贡献1812条经验 获得超5个赞

将注释放在 getter 上。

也许私有字段不支持验证。


查看完整回答
反对 回复 2023-09-27
  • 4 回答
  • 0 关注
  • 80 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信