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

我在HSQL中发现了一个奇怪的行为,似乎在使用数据库事务时,在SQL插入期间没有检查数据库约束,但在SQL提交期间以及当事务被回滚时,它们根本不会被检查.

我有一个Spring集成测试:

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

使用测试创建一个新的实体实例并调用Hibernate的持久性.

它运行正常,但是当我将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 atttribute.

问题:

>为什么在插入期间但在提交期间不检查数据库约束?
>为什么在做回滚数据库时没有检查约束?

最佳答案 [发布@ a_horse_with_no_name的答案,只是为了能够关闭这个问题].

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

点赞