我有一个基于Spring的JPA2应用与HSQLDB上的Hibernate提供程序。我试图优雅地处理异常,但我发现我正在获取休眠异常而不是JPA异常。例如:HSQLDB不会抛出正确类型的ConstraintViolationException与Spring JPA /休眠
import javax.validation.ConstraintViolationException;
...
@Override
@Transactional
public Result<Document> save(Document document) {
try {
store.persist(document);
return new Success<Document>(document);
}
catch (EntityExistsException e) {
return new Errors<Document>(DocumentError.DOCUMENT_ALREADY_EXISTS);
}
catch (ConstraintViolationException e) {
return new Errors<Document>(DocumentError.CONSTRAINT_VOILATION);
}
catch (PersistenceException e) {
return new Errors<Document>(DocumentError.UNKOWN_EXCEPTION);
}
}
而是被扔javax.validation.ConstraintViolationException的我抓的PersistenceException:
javax.persistence.PersistenceException:org.hibernate.exception.ConstraintViolationException:无法插入:[文件]
我在Spring配置中配置的JpaAdapter:
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="org.hsqldb.jdbcDriver"
p:url="jdbc:hsqldb:file:target/db/intox"
p:username="sa"
p:password=""
/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory"/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="jpaAdapter"/>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
<property name="persistenceUnitName" value="p"/>
</bean>
<bean id="entityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="HSQL"
p:showSql="false"/>
任何人都可以建议如何或为什么我得到Hibernate异常而不是JPA(javax.persistence)?
附加信息:
春3.1.0.M2
的Hibernate 3.5.4决赛
Hibernate验证4.1.0.Final
HSQLDB 2.0.0
我期待着一个异常,但我期待javax.validation.ConstraintViolationException不是javax.persistence.PersistenceException:org.hibernate.exception.ConstraintViolationException – SilentICE
不要这样做,显然你没有违反任何这样的验证约束,它会导致引发javax.validation.ConstraintViolationException。这种异常来自JSR-303验证注释。你得到的是因为我在答案中解释的原因。 –
是的我现在看到验证约束vs数据库约束谢谢 – SilentICE