如何将自定义方法添加到 Spring Data JPA

新手上路,请多包涵

我正在研究 Spring Data JPA。考虑下面的示例,我将默认使用所有 crud 和 finder 功能,如果我想自定义 finder,那么也可以在界面本身中轻松完成。

 @Transactional(readOnly = true)
public interface AccountRepository extends JpaRepository<Account, Long> {

  @Query("<JPQ statement here>")
  List<Account> findByCustomer(Customer customer);
}

我想知道如何为上述 AccountRepository 添加一个完整的自定义方法及其实现?由于它是一个接口,我无法在那里实现该方法。

原文由 Sharad Yadav 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 448
2 个回答

您需要为您的自定义方法创建一个单独的接口:

 public interface AccountRepository
    extends JpaRepository<Account, Long>, AccountRepositoryCustom { ... }

public interface AccountRepositoryCustom {
    public void customMethod();
}

并为该接口提供一个实现类:

 public class AccountRepositoryImpl implements AccountRepositoryCustom {

    @Autowired
    @Lazy
    AccountRepository accountRepository;  /* Optional - if you need it */

    public void customMethod() { ... }
}

也可以看看:

原文由 axtavt 发布,翻译遵循 CC BY-SA 4.0 许可协议

除了 axtavt 的 答案 之外,如果您需要它来构建查询,请不要忘记您可以在自定义实现中注入实体管理器:

 public class AccountRepositoryImpl implements AccountRepositoryCustom {

    @PersistenceContext
    private EntityManager em;

    public void customMethod() {
        ...
        em.createQuery(yourCriteria);
        ...
    }
}

原文由 jelies 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题