问题
I made a custom validation annotation for unique email (When user registers itself, program checks if email is already in database).
Everything works just fine, but when I need to modify user's info and not to create a new one I run into a problem that says "Email is already in use"
Can I somehow turn off only @UniqueEmail
validation(I need the others like email pattern and password validation)?
All validation annotations are in the same User bean.
Thank You.
回答1:
I'm going to assume that you are using javax.validation
.
First you need an interface OnUpdate
:
javax.validation.groups.Default
public interface OnUpdate extends Default {}
Now you need to set all the annotations that need to only run on UPDATE
:
@NotNull(groups = OnUpdate.class)
Now, you have divided your validations into two groups, those in OnUpdate
and those in Default
. Running Default
will include those in OnUpdate
as OnUpdate
extends Default
.
Now, this is where it gets a little tricky - you need to tell the framework which validations to run on each task.
If using JPA you just need to set the following property:
javax.persistence.validation.group.pre-update = com.my.package.OnUpdate
回答2:
Further to Boris The Spider's answer, if you want to do this in code rather than with persistence.xml you can create the following bean:
@Bean
public HibernatePropertiesCustomizer hibernatePropertiesCustomizer(final Validator validator) {
return new HibernatePropertiesCustomizer() {
@Override
public void customize(Map<String, Object> hibernateProperties) {
@SuppressWarnings("rawtypes")
Class[] classes = {OnUpdate.class};
hibernateProperties.put("javax.persistence.validation.group.pre-update", classes);
}
};
}
来源:https://stackoverflow.com/questions/36567917/how-to-prevent-spring-validation-on-update