我怎样才能实现这个代码的等效:
tx.begin();
Widget w = em.find(Widget.class, 1L, LockModeType.PESSIMISTIC_WRITE);
w.decrementBy(4);
em.flush();
tx.commit();
...但是使用 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);
}
}
但我不知道如何指定 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
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.
...所以这似乎没有帮助。
如何让我的 updateWidgetStock()
方法在设置 LockModeType.PESSIMISTIC_WRITE
的情况下执行?
最佳答案
@Lock
从 Spring Data JPA 1.6 版开始支持 CRUD 方法(事实上,已经有 milestone 可用)。看到这个ticket了解更多详情。
使用该版本,您只需声明以下内容:
interface WidgetRepository extends Repository<Widget, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
Widget findOne(Long id);
}
这将导致后备存储库代理的 CRUD 实现部分将配置的 LockModeType
应用到 EntityManager
上的 find(...)
调用>.
关于java - 使用 Spring Data JPA 查找实体时如何启用 LockModeType.PESSIMISTIC_WRITE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16159396/