我正在研究Spring Data JPA.考虑下面的示例,我将默认使用所有crud和finder功能,如果我想自定义查找器,那么也可以在界面本身轻松完成.
@Transactional(readOnly = true)
public interface AccountRepository extends JpaRepository<Account, Long> {
@Query("<JPQ statement here>")
List<Account> findByCustomer(Customer customer);
}
Run Code Online (Sandbox Code Playgroud)
我想知道如何为上述AccountRepository添加一个完整的自定义方法及其实现?由于它的接口我无法在那里实现该方法.
如何实现此代码的等价物:
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 …