我正在開發使用Spring MVC Web應用程序,並在我的應用這樣的方法:競爭條件
@Transactional
public void methodA(Long id, String color) {
Fruit fruit = entityManager.createNamedQuery("Fruit.findById", Fruit.class).setParameter(1, id).getSingleResult();
fruit.setColor("color");
entityManager.merge(fruit);
}
@Transactional
public void methodB(Long id, int price) {
Fruit fruit = entityManager.createNamedQuery("Fruit.findById", Fruit.class).setParameter(1, id).getSingleResult();
fruit.setPrice(price);
entityManager.merge(fruit);
}
這兩種方法往往是在同一時間差點叫,正因爲這樣的競爭條件發生。有沒有辦法解決這個問題?我認爲把它們放在一個同步的方法中並不是一個好主意,因爲我期望不同用戶同時調用這些方法(數千個)很多,所以會導致延遲。修復我,如果我錯了。
值得一提的是,您複雜而昂貴的查詢只是'entityManager.find(Fruit.class,id)'。 – chrylis
這種方法是在服務中還是在DAO(或存儲庫)中? –
@KimAragonEscobar,它位於存儲庫類中。存儲庫類在服務類中 –