SpringFramework: @Transactional(readOnly = true) not working with h2

非 Y 不嫁゛ 提交于 2020-06-27 09:10:26

问题


I am doing transaction testing with the SpringFramework. I have the following classes.

UserService.class

@Transactional
public interface UserService {
    void add(User user);

    @Transactional(readOnly = true)
    User get(String id);

    @Transactional(readOnly = true)
    List<User> getAll();

    void deleteAll();

    void update(User user);
}

UserServiceImpl.class

public class UserServiceImpl implements UserService {
    // skip some methods
    @Override public void update(User user) { userDao.update(user); }
}

TestUserService.class

public class TestUserService extends UserServiceImpl {
    @Override
    public List<User> getAll() {
        for (User user : super.getAll()) {
            // try to update in get* method. it's read-only. 
            super.update(user);
        }
        return null;
    }
}

Test Code

@Test(expected = TransientDataAccessResourceException.class)
public void readOnlyTransactionAttribute() {
    testUserService.getAll();
}

This test code is a success case when using mysql. But it fails when using H2 In-memory database. This is because the transaction completes without an exception.

I read the Spring Framework documentation and found the following: http://docs.spring.io/spring/docs/4.3.x/javadoc-api/org/springframework/transaction/annotation/Transactional.html#readOnly--

This just serves as a hint for the actual transaction subsystem; it will not necessarily cause failure of write access attempts. A transaction manager which cannot interpret the read-only hint will not throw an exception when asked for a read-only transaction but rather silently ignore the hint.

But I wonder if there is a way to pass this test with the H2 database.

来源:https://stackoverflow.com/questions/44499137/springframework-transactionalreadonly-true-not-working-with-h2

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