Sunday, November 25, 2012

Hibernate InvalidStateException - How to identify invalid fields

    If you are using Hibernate, you should be familiar with the InvalidStateException which is thrown when you are going to persist data to a table with invalid values. Simply by looking at the stack trace it is impossible to find the table columns or Entity fields for which the validations are failed.
    But actually it is not very difficult to find those fields. First you need to catch the InvalidStateException by using a try-catch block. The InvalidStateException class has a method getInvalidValues() which returns an array of InvalidValue s. In this InvalidValue class there are several methods to find the information you need. So by Iterating through this array you can get the info you need.
try {
  //Persistence logic here...
} catch (InvalidStateException e) {
  for(InvalidValue invalidValue : e.getInvalidValues()) {
    System.out.println(invalidValue.getPropertyName());//Property on which validations
                                                       are failed
    System.out.println(invalidValue.getValue());//invalid value
    System.out.println(invalidValue.getMessage());//message for invalid value
    System.out.println(invalidValue.getBeanClass());//Entity bean which belongs the
                                                    property
  }
}

No comments:

Post a Comment