Pompey Magnus
Pompey Magnus

Reputation: 2341

Hibernate Validator - optional validation depending on lifecycle

Just started using Hibernate Validator. I have a case where a bean's id is autogenerated when saved. I'd live to validate the bean before the save. At which time the id can be null. However, when I want to update it the id must be notnull.

So the generic @NotNull on the field won't work because when I go to save it it will fail validation.

There are ways to work around this, but I was wondering if the spec or hibernate implementation have a standard way of doing this. I'd like to not have any validation errors on save and no validation on update.

Such as applying a constraint but it's ignored unless implicitly named or something like that.

Thanks in advance.

Upvotes: 1

Views: 662

Answers (1)

Khalid
Khalid

Reputation: 2230

You can achieve that with groups.

public class MyBean {
    @NotNull(groups = UpdateBean.class)
    private Long id;
}

Validate without the id:

validator.validate(myBean);

Validate with the id:

validator.validate(myBean, UpdateBean.class);

Upvotes: 2

Related Questions