I have next spring rest controller for handle my exception:
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
pub
Try to reproduce next steps:
@Bean public MethodValidationPostProcessor methodValidationPostProcessor() { return new MethodValidationPostProcessor(); }
mark your Controller with @Validated
Mark your paramater in Controller's method with
@Pattern(regexp = "\\d+") @RequestParam String param
If you want to use that Entity. Do something like
@Valid @RequestBody Device device
in your method. And you can skip all previous steps.
Reason for TransactionSystemException
If you go inside the code AbstractEntityManagerImpl.convert() method, you will see that by default it's not handling any specific exception like ConstraintViolation instead it just throws and wraps in PersistenceException.
Solution for correctly resolving your exception
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> <property name="jpaDialect" ref="jpaDialect"/> </bean> <bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
HibernateJpaDialect catches those exception and converts to spring specific exceptions like this
if (ex instanceof ConstraintViolationException) { ConstraintViolationException jdbcEx = (ConstraintViolationException) ex; return new DataIntegrityViolationException(ex.getMessage() + "; SQL [" + jdbcEx.getSQL() + "]; constraint [" + jdbcEx.getConstraintName() + "]", ex); }
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="packagesToScan" value="com.pack.model" /> <property name="persistenceUnitManager" ref="persistenceUnitManager"/> <property name="persistenceUnitName" value="entityManager"/> <property name="jpaVendorAdapter" ref="jpaVendorAdapter"/> </bean> <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
@ExceptionHandler(DataIntegrityViolationException.class)