为什么在Hibernate中使用事务时,HSQLDB中的数据库约束只在提交期间检查



我在HSQL中发现了一个奇怪的行为,当使用数据库事务时,似乎在SQL插入期间不检查数据库约束,但在SQL提交期间,当事务回滚时,根本不检查这些约束。

我有一个Spring集成测试:

@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(defaultRollback=true, transactionManager="transactionManager")
@Transactional
public class IntegrationTest {

通过创建一个新实体实例并在其上调用Hibernate的persist的测试

它工作正常,但当我将defaultRollback更改为false时,它失败了:

Caught exception while allowing TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener@517a2b0] to process 'after' execution for test: method [public void MyIntegrationTest.test()], instance [MyIntegrationTest@546e61d5], exception [null]
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
  at org.springframework.orm.hibernate4.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:161)
  at org.springframework.orm.hibernate4.HibernateTransactionManager.convertHibernateAccessException(HibernateTransactionManager.java:681)
  at org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:563)
  at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:757)
  at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:726)
...
Caused by: java.sql.SQLIntegrityConstraintViolationException: integrity constraint violation: NOT NULL check constraint; SYS_CT_10120 table: MYTABLE column: MYCOLUMN

这似乎是正确的,因为实际上我的代码在调用实体上的persist之前没有在实体中设置mycolumn attribution

问题:

  • 为什么在插入时不检查数据库约束,而在提交时检查数据库约束
  • 为什么在执行回滚时不检查数据库约束

[发布@a_hors_with_no_name的答案,只是为了能够结束这个问题]。

我的ORM(Hibernate)在提交之前没有向数据库发送查询。如果事务以回滚结束,则根本不会将查询发送到数据库。确保在每次persis()修复问题后调用flush()FlushMode.ALWAYS)。

最新更新