首页 > 解决方案 > Spring数据,派生存储库方法

问题描述

我有一个工作的 mongo 存储库

@Repository
interface NewsRepository : ReactiveMongoRepository<News, String> {

    fun findByUserId(userId: String): Flux<News>

    fun findByType(type: NewsType, pageable: Pageable): Flux<News>

    fun countByType(type: NewsType): Long
}

服务可以调用这个存储库的findByUserIdfindByType方法并返回一个新闻列表。

一旦我打电话,countByType我就会得到以下异常:

System.out.println(newsRepository.countByType(NewsType.OFFICIAL))

19-10-28 14:44:25.131 调试 2986 --- [ctor-http-nio-4] osdmrquery.MongoQueryCreator:创建查询查询:{“type”:{“$java”:官方}},字段:{ },排序:{} 2019-10-28 14:44:25.165 错误 2986 --- [ctor-http-nio-4] awreAbstractErrorWebExceptionHandler : [a29dfc95] HTTP GET "/api/user/news/pages 的 500 服务器错误"

java.lang.ClassCastException:reactor.core.publisher.MonoOnErrorResume 无法在 com.sun.proxy.$Proxy171.countByType(Unknown Source) ~[na:na] at sun.reflect.NativeMethodAccessorImpl 处转换为 java.lang.Long。在 sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_151] 处调用0(本机方法)~[na:1.8.0_151]

我猜这与 ReactiveMongoRepository 签名有关<News, String>

countByxxx似乎是一件事(https://www.logicbig.com/tutorials/spring-framework/spring-data/derived-count-query.html),因为findByType工作我很困惑......

标签: mongodbkotlinspring-data-jpa

解决方案


看起来在 ReactiveMongoRepository 中我不能有一个返回“非反应性”数据类型的方法。

所以除了原来的NewsRepository我创建了一个NewsAggregationRepository看起来像

@Repository
interface NewsAggregationRepository: CrudRepository<News, Long> {

    fun countByType(type: NewsType): Long
}

这次它扩展了 CrudRepository

我可以将这个存储库沿反应式注入到我的服务中:

class NewsServiceImpl(private val newsRepository: NewsRepository, private val newsAggregationRepository: NewsAggregationRepository)

并从那里调用反应和非反应方法

sysout(newsAggregationRepository.countByType(xxx))
sysout(newsRepository.getNews())

推荐阅读