Issue with @Transactional annotations in Spring JPA

只谈情不闲聊 提交于 2019-12-06 15:57:44

I think that the default behaviour is (even thought you don't have it on the test class)

@TransactionConfiguration(defaultRollback = true)

so it will perform rollback when your test ends. Therefore there is no synchronization of hibernate session with the database and no queries SQL are issued to the database.

You have two posibilities. Either specify

@TransactionConfiguration(defaultRollback = false)

or inject entity manager into your test and call

@PersistenceContext
protected EntityManager em;

/**
 * Simulates new transaction (empties Entity Manager cache).
 */
public void simulateNewTransaction() {
    em.flush();
    em.clear();
}

This will force hibernate to send all queries to the database. Please note that this will solve your problem with deleting non existing entity, but it doesn't behave exactly like new transaction, e.g. when you have missing foreign key it doesn't throw anything (this is predictable.

You can use this for checking the contents of entity returned by em.find(class, id) and check you relational mapping without the need to commit the transaction.

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