spring-data-jpa bean validation in junit tests

谁说我不能喝 提交于 2019-11-30 13:27:52
andyb

I managed to reproduce the problem exactly described in the question locally, albeit after adding back the missing get/set functions and the UserRepository class :-)

After some digging I found two existing questions JPA ConstraintViolation vs Rollback and Hibernate not following JPA specifications when combined with Bean Validation API?

Both seem to conclude that Hibernate is not throwing the ConstraintValidationException correctly.

The outcome of the second question was a defect HHH-8028 - entityManager.persist not throwing ConstraintValidationException being raised against Hibernate.

To confirm this was the same issue, I switched to a simple @GeneratedValue and insertWrongEmail passed. insertToShortPassword was still failing but I put that down to a missing @Size(min = 6) on the password field. After adding that, all tests passed.

Reverting back to your configured @GeneratedValue I then swapped Hibernate for the EclipseLink persistence framework. Both tests passed which seems to confirm the discovery from the previous questions. The changes I made were:

pom.xml changes add the jpa artifact as described on the EclipseLink site

<dependency>
   <groupId>org.eclipse.persistence</groupId>
   <artifactId>org.eclipse.persistence.jpa</artifactId>
   <version>2.4.0</version>
   <scope>compile</scope>
</dependency>

test-context.xml changes

Switch to EclipseLinkJpaVendorAdapter

<bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter"
    p:generateDdl="true" p:database="HSQL" />

Add eclipselink.weaving property, as detailed on EclipseLinkJpaVendorAdapter instead of HibernateJpaVendorAdapter issue

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="jpaAdapter" >
    <!-- existing configuration is identical -->
    <property name="jpaPropertyMap">
      <map>
        <entry key="eclipselink.weaving" value="false"/>
      </map>
    </property>
</bean>

User.java changes

I needed to add a default no-argument constructor. You might already have one in the full User.java class.

Flushing the persistence context after executing the repository operation might do the trick. JPA invokes Bean Validation only when synchronizing with the database, i.e. during commit or a flush.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!