问题
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