【发布时间】:2020-06-07 22:23:15
【问题描述】:
我有这个项目试图检查事务隔离。我从 READ_UNCOMMITTED 级别开始,但它不起作用。 代码非常简单。
主类
@SpringBootApplication
@EnableTransactionManagement
public class HibernateTransactionsLocksTestApplication {
public static void main(String[] args) {
SpringApplication.run(HibernateTransactionsLocksTestApplication.class, args);
}
}
控制器
@RestController
public class HomeController {
private final AccountService accountService;
public HomeController(AccountService accountService) {
this.accountService = accountService;
}
@GetMapping("/updateAccount2RU")
public String updateAccount2RU() throws InterruptedException {
accountService.updateAccount2RU();
return "done!";
}
@GetMapping("/update2Account2RU")
public String update2Account2RU() throws InterruptedException {
accountService.update2Account2RU();
return "done!";
}
}
服务
@Service
public class AccountService {
private final AccountRepository accountRepository;
public AccountService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void updateAccount2RU() throws InterruptedException {
Account a = accountRepository.findById(2).get();
System.out.println("Account amount: " + a.getAmount());
a.setAmount(a.getAmount()+1);
accountRepository.save(a);
Thread.currentThread().sleep(5000);
}
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void update2Account2RU() throws InterruptedException {
Account a = accountRepository.findById(2).get();
System.out.println("Account amount: " + a.getAmount());
a.setAmount(a.getAmount()+1);
Thread.currentThread().sleep(5000);
}
}
Repository 是一个简单的 SpringData 存储库
@Repository
public interface AccountRepository extends JpaRepository<Account, Integer> {
@Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_UNCOMMITTED)
Account findByName(String name);
}
application.properties
server.contextPath=/
spring.datasource.url=jdbc:mysql://localhost:3306/trasactions-locks-tests
spring.datasource.username=
spring.datasource.password=
spring.jpa.properties.hibernate.dialect =org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
#spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
spring.jpa.open-in-view=false
#Check transactions behaviour
logging.level.org.springframework.transaction.interceptor=TRACE
基本上我在 Chrome 中打开 2 个选项卡并访问 updateAccount2RU(这应该读取帐户并增加金额,线程应该在醒来并提交事务之前休眠 5 秒)同时我访问第二种方法 update2Account2RU读取相同的帐户,并且从第一种方法读取的金额相同,而不是更新的方法。
【问题讨论】:
标签: hibernate spring-boot transactions spring-data-jpa