使用Spring Data JPA查找实体时如何启用LockModeType.PESSIMISTIC_WRITE? [英] How to enable LockModeType.PESSIMISTIC_WRITE when looking up entities with Spring Data JPA?
问题描述
我该如何实现与以下代码等效的功能:
How can I achieve the equivalent of this code:
tx.begin();
Widget w = em.find(Widget.class, 1L, LockModeType.PESSIMISTIC_WRITE);
w.decrementBy(4);
em.flush();
tx.commit();
...但是使用Spring和Spring-Data-JPA批注?
... but using Spring and Spring-Data-JPA annotations?
我现有代码的基础是:
@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);
}
}
但是我不知道如何指定updateWidgetStock
方法中的所有操作都应使用悲观锁设置.
But I don't know how to specify that everything in the updateWidgetStock
method should be done with a pessimistic lock set.
有一个Spring Data JPA批注org.springframework.data.jpa.repository.Lock
,它允许您设置LockModeType
,但是我不知道将其放在updateWidgetStock
方法上是否有效.听起来更像是WidgetRepository
上的注释,因为Javadoc说:
There is a Spring Data JPA annotation org.springframework.data.jpa.repository.Lock
which allows you to set a LockModeType
, but I don't know if it's valid to put it on the updateWidgetStock
method. It sounds more like an annotation on the WidgetRepository
, because the Javadoc says:
org.springframework.data.jpa.repository
@Target(value = METHOD)
@Retention(value = RUNTIME)
@Documented
public @interface锁
用于指定执行查询时要使用的LockModeType的注释.在查询方法上使用Query或从方法名称派生查询时,将对它进行评估.
org.springframework.data.jpa.repository
@Target(value=METHOD)
@Retention(value=RUNTIME)
@Documented
public @interface Lock
Annotation used to specify the LockModeType to be used when executing the query. It will be evaluated when using Query on a query method or if you derive the query from the method name.
...所以似乎没有帮助.
... so that doesn't seem to be helpful.
如何在设置了LockModeType.PESSIMISTIC_WRITE
的情况下执行我的updateWidgetStock()
方法?
How can I make my updateWidgetStock()
method execute with LockModeType.PESSIMISTIC_WRITE
set?
推荐答案
@Lock
(实际上,已经有一个门票.
@Lock
is supported on CRUD methods as of version 1.6 of Spring Data JPA (in fact, there's already a milestone available). See this ticket for more details.
使用该版本,您只需声明以下内容:
With that version you simply declare the following:
interface WidgetRepository extends Repository<Widget, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
Widget findOne(Long id);
}
这将导致后备存储库代理的CRUD实现部分将配置的LockModeType
应用于EntityManager
上的find(…)
调用.
This will cause the CRUD implementation part of the backing repository proxy to apply the configured LockModeType
to the find(…)
call on the EntityManager
.
这篇关于使用Spring Data JPA查找实体时如何启用LockModeType.PESSIMISTIC_WRITE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!