0

The controller throws an ConstraintViolationException since the JPA Entity has a Pattern matching check for field role, which is enforced via Hibernate. But the Controller Advice receives the above exception as TransactionSystemException instead. Its not clear why the original exception is getting masked in the first place.

@Entity
public class Bar {

    @Pattern(regexp = "^role-.*", message = "Role should conform to naming conventions")
    private String role;
}

The exception being thrown

Spring Controller Advice receives TransactionSystemException instead of ConstraintViolationException

    org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
            at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:571) ~[spring-orm-5.3.22.jar:5.3.22]

      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
    
            at java.lang.Thread.run(Thread.java:831) ~[?:?]
    
    Caused by: javax.persistence.RollbackException: Error while committing the transaction

        at org.hibernate.internal.ExceptionConverterImpl.convertCommitException(ExceptionConverterImpl.java:81) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]

        at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:104) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]

        at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:562) ~[spring-orm-5.3.22.jar:5.3.22]

        ... 112 more

Caused by: javax.validation.ConstraintViolationException: Validation failed for classes [com.foo.model.Bar] during update time for groups [javax.validation.groups.Default, ]

List of constraint violations:[

        ConstraintViolationImpl{interpolatedMessage='Role should conform to naming conventions', propertyPath=role, rootBeanClass=class com.foo.model.Bar, messageTemplate='Role should conform to naming conventions'}

]
        at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:140) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
Rpj
  • 5,348
  • 16
  • 62
  • 122
  • 1
    Check this answer: https://stackoverflow.com/questions/40808319/hibernate-validation-results-in-spring-transactionsystemexception – Mustafa Kannan Sep 26 '22 at 13:07

0 Answers0