Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 6th, 2012  |  syntax: None  |  size: 2.24 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Is there any configuration necessary to use Hibernate Validation custom messages
  2. public class BeanValidationTool {
  3.  
  4.     public void validate(Object entity) {
  5.         TraversableResolver tr = new MyTraversableResolver();
  6.         Validator validator = Validation.buildDefaultValidatorFactory().usingContext().traversableResolver(tr).getValidator();
  7.         final Set<ConstraintViolation<Object>> constraintViolations = validator.validate(entity);
  8.         if (constraintViolations.size() > 0) {
  9.           Set<ConstraintViolation<?>> propagatedViolations = new HashSet<ConstraintViolation<?>>(constraintViolations.size());
  10.           Set<String> classNames = new HashSet<String>();
  11.             for (ConstraintViolation<?> violation : constraintViolations) {
  12.               propagatedViolations.add(violation);
  13.               classNames.add(violation.getLeafBean().getClass().getName());
  14.             }
  15.             StringBuilder builder = new StringBuilder();
  16.             builder.append("validation failed for classes ");
  17.             builder.append(classNames);
  18.             throw new ConstraintViolationException(builder.toString(), propagatedViolations);
  19.         }
  20.     }
  21.  
  22.     public class MyTraversableResolver  implements TraversableResolver {
  23.  
  24.         public boolean isReachable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) {
  25.             return traversableObject == null || Hibernate.isInitialized(traversableObject);
  26.         }
  27.  
  28.         public boolean isCascadable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) {
  29.             return true;
  30.         }
  31.     }
  32.   }`
  33.        
  34. validator.min = must be greater than or equal to {value}
  35.  
  36. validator.notEmpty = This field can't be empty
  37.        
  38. <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" abstract="false"
  39.       scope="singleton" lazy-init="default">
  40.     <property name="basename" value="ValidationMessages"/>
  41. </bean>
  42.        
  43. @Autowired
  44. private MessageSource messageSource;
  45.  
  46. public String getMessage(String messageName) {
  47.     return messageSource.getMessage(messageName, null, null);
  48. }
  49.        
  50. @Component
  51. public class BeanValidationTool{...