如何实现此代码的等价物:
tx.begin();
Widget w = em.find(Widget.class, 1L, LockModeType.PESSIMISTIC_WRITE);
w.decrementBy(4);
em.flush();
tx.commit();
Run Code Online (Sandbox Code Playgroud)
...但是使用Spring和Spring-Data-JPA注释?
我现有代码的基础是:
@Service
@Transactional(readOnly = true)
public class WidgetServiceImpl implements WidgetService
{
/** The spring-data widget repository which extends CrudRepository<Widget, Long>. */
@Autowired
private WidgetRepository repo;
@Transactional(readOnly = false)
public void updateWidgetStock(Long id, int count)
{
Widget w = this.repo.findOne(id);
w.decrementBy(4);
this.repo.save(w);
}
}
Run Code Online (Sandbox Code Playgroud)
但我不知道如何指定updateWidgetStock方法中的所有内容都应该使用悲观的锁定集来完成.
有一个Spring Data JPA注释org.springframework.data.jpa.repository.Lock允许你设置一个LockModeType,但我不知道将它放在updateWidgetStock方法上是否有效.这听起来更像是一个注释WidgetRepository,因为Javadoc说:
org.springframework.data.jpa.repository
@Target(value = METHOD)
@Retention(value = RUNTIME)
@Documented
public @interface Lock …