开发者

Spring Test Transaction Rollback Problem

i have a Problem understanding the @Transactional and @TransactionConfiguration(defaultRollback = true) Annotations.

I 开发者_开发技巧have a test Code which inserts a userAccount into the Database, then another account with the same name should be inserted, which should result in a DataIntegrityViolationException because the AccountName is marked as Unique. This works fine if @Transactional and @TransactionConfiguration(defaultRollback = true) is not sepcified at the TestClass level. But if Rollback is enabled i don't get the Exception because even in the same method the Data is not inserted into the databasse. If i set a breakpoint after inserting the first Account, the Database is still empty.

Here is my Code:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/spring/applicationContext.xml"})
@Transactional
@TransactionConfiguration(defaultRollback = true)
public class DaoTests {

    @Autowired
    private Repository repo;
    @Autowired
    private AccountService userService;

    @Before
    public void orgInstAccount() {
        Organization o = new Organization();
        o.setName("Organisation 1");
        repo.saveEntity(o);

        Institution i1 = new Institution();
        i1.setName("xyz");
        i1.setOwningOrganization(o);
        repo.saveEntity(i1);

    }

    @Test(expected = DataIntegrityViolationException.class)
    public void saveUserFail() {

        Account user = new Account();
        user.setAccountname("chz");
        user.setPassword(userService.calcMD5Hash("123"));
        user.setOwningInstitution(repo.getInstitutionByName("xyz"));
        repo.saveEntity(user);
        Assert.assertNotNull(repo.getAccountByName("chz"));


        Account userNew = new Account();
        userNew.setAccountname("chz");
        userNew.setPassword(userService.calcMD5Hash("123"));
        userNew.setOwningInstitution(repo.getInstitutionByName("xyz"));
        repo.saveEntity(userNew);
        //Here the Exception should be thrown but everything works fine.

    }

}

The Repository Implementation is:

@Repository
@Transactional
@SuppressWarnings("unchecked")
public class RepositoryHibernateImpl implements Repository {

    @Autowired
    private SessionFactory factory;

    @Override
    public void saveEntity(Entity hce) {
        factory.getCurrentSession().save(hce);
    }
}

Maybe the Problem is because the Repository and the TestClass are marked with @Transactional?

Thank you in Advance.


Call flush() which will try to call sql immediatly instead of deferring it till transaction boundary

factory.getCurrentSession().flush()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜