简体   繁体   English

实现一个spring数据仓库接口中的常规接口

[英]Implement a regular interface in a spring data repository interface

I'm using a Repository that extends a spring data JpaRepository and would like to let it extend another interface.我正在使用一个扩展 spring 数据 JpaRepository 的存储库,并想让它扩展另一个接口。

Previously, my db repository looked like this:以前,我的数据库存储库如下所示:

interface PublicTransportPricingZoneRepository : JpaRepository<PublicTransportPricingZone, Long> {

}

I have now created another interface TransitTicketRepo as defined below我现在创建了另一个接口TransitTicketRepo ,定义如下

interface TransitTicketRepo {
    fun findPossibleTickets(geometry: Geometry): Collection<TransitTicket>
}

and now would like to implement the interface with a default method in PublicTransportPricingZoneRepository .现在想使用PublicTransportPricingZoneRepository中的默认方法实现接口。 I've tried to solve this by changing the code of my PublicTransportPricingZoneRepository to我试图通过将 PublicTransportPricingZoneRepository 的代码更改为来解决这个问题

interface PublicTransportPricingZoneRepository : JpaRepository<PublicTransportPricingZone, Long>, TransitTicketRepo {
    fun findPossibleTickets(geometry: Geometry): Collection<TransitTicket> {
       // do something
       return emptyList()
    } 
}

but get the following error message when starting the application.但是在启动应用程序时收到以下错误消息。

org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.Collection PublicTransportPricingZoneRepository.findPossibleTickets(Geometry); Reason: Failed to create query for method public abstract java.util.Collection...

I'm assuming the solution is to somehow tell spring data to stop auto-generating a query for findPossibleTickets but have been unable to find out how.我假设解决方案是以某种方式告诉 spring 数据停止自动生成findPossibleTickets的查询,但一直无法找出如何。

You can do it this way你可以这样

In short.:简而言之。:

@Repository
// Your bean that will be glued together by spring
interface PublicTransportPricingZoneRepository extends JpaRepository<...>, PublicTransportPricingZoneCustomRepository {
  // Other methods, but everything must be annotated with @Query or possible for spring to guess what it needs to do from its name (google derived methods)
}

interface PublicTransportPricingZoneCustomRepository {
  // define custom methods
  List<String> nameIsNotImportant();
}

@Service
// naming here is important - it must be names as interface + Impl, otherwise spring won't pick it up
// apart from that, it's a regular bean - you can Autowire, etc
class PublicTransportPricingZoneCustomRepositoryImpl implementats PublicTransportPricingZoneCustomRepository {
  // Implement custom methods
  @Overridden
  public List<String> nameIsNotImportant() {
    // impl
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM