Last active
          December 28, 2019 19:53 
        
      - 
      
 - 
        
Save abitgen/a0c248e68c5b2180ebbc70c1450d10a5 to your computer and use it in GitHub Desktop.  
    Validating entity manually, accepts entityManager and the entity to validate as parameters
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | public static <T> String validateEntity(final EntityManager entityManager, T obj){ | |
| Validator validator = new HibernateValidator().buildValidatorFactory(new ConfigurationState() { | |
| @Override | |
| public boolean isIgnoreXmlConfiguration() { | |
| return true; | |
| } | |
| @Override | |
| public MessageInterpolator getMessageInterpolator() { | |
| return new ResourceBundleMessageInterpolator(); | |
| } | |
| @Override | |
| public Set<InputStream> getMappingStreams() { | |
| return new HashSet<>(); | |
| } | |
| @Override | |
| public ConstraintValidatorFactory getConstraintValidatorFactory() { | |
| return new ConstraintValidatorFactoryImpl(); | |
| } | |
| @Override | |
| public TraversableResolver getTraversableResolver() { | |
| return new EntityManagerJpaTraversable(entityManager); | |
| } | |
| @Override | |
| public ParameterNameProvider getParameterNameProvider() { | |
| return null; | |
| } | |
| @Override | |
| public Map<String, String> getProperties() { | |
| return new HashMap<>(); | |
| } | |
| }).getValidator(); | |
| Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj); | |
| if (constraintViolations.size() > 0) { | |
| Set<String> violationMessages = new HashSet<>(); | |
| for (ConstraintViolation<T> constraintViolation : constraintViolations) { | |
| violationMessages.add(constraintViolation.getPropertyPath() + ": " + constraintViolation.getMessage()); | |
| } | |
| return obj.getClass().getSimpleName() + " is not valid: \n " + violationMessages.toString() + " \n "; | |
| } | |
| return null; | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment