java - Unique column validator in Spring -


i want add validator return error if value not unique. how this? current validator:

@component public class addformvalidator implements validator {     public boolean supports(class<?> clazz) {         return addform.class.isassignablefrom(clazz);     }      public void validate(object target, errors errors) {         addform addform = (addform) target;          validationutils.rejectifemptyorwhitespace(errors, "title",                 "title.empty", "title must not empty.");         string title = addform.gettitle();         if ((title.length()) > 30) {             errors.rejectvalue("title", "title.toolong",                     "title must not more 16 characters.");         }          validationutils.rejectifemptyorwhitespace(errors, "content",                 "content.empty", "content must not empty.");         string content = addform.getcontent();         if ((content.length()) > 10000) {             errors.rejectvalue("content", "content.toolong",                     "content must not more 10k characters.");         }      } 

i want validate title.

i don't know how doing database access, should inject repository query database check if title exist. :

@component public class addformvalidator implements validator {      @autowired     newsrepository newsrepository;             public boolean supports(class<?> clazz) {         return addform.class.isassignablefrom(clazz);     }      public void validate(object target, errors errors) {         addform addform = (addform) target;          validationutils.rejectifemptyorwhitespace(errors, "title",                 "title.empty", "title must not empty.");         string title = addform.gettitle();         if ((title.length()) > 30) {             errors.rejectvalue("title", "title.toolong",                     "title must not more 16 characters.");         }          new new = newsrepository.findbytitle(title);         // new exist         if (new != null) {             errors.rejectvalue("title", "title.alreadyexist",                     "new title exist");         }          validationutils.rejectifemptyorwhitespace(errors, "content",                 "content.empty", "content must not empty.");         string content = addform.getcontent();         if ((content.length()) > 10000) {             errors.rejectvalue("content", "content.toolong",                     "content must not more 10k characters.");         }      } } 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

.htaccess - Matching full URL in RewriteCond -