mongodb - 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
}
服务可以调用这个存储库的findByUserId
和findByType
方法并返回一个新闻列表。
一旦我打电话,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
工作我很困惑......
解决方案
看起来在 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())
推荐阅读
- kubernetes - 使用 istio 作为外部 TLS 服务的反向代理
- android - 在片段 Kotlin 中使用 ContextCompat.getColor?
- javascript - 在 rgba 问题中替换 alpha
- python - 将x位数转换为两位数
- ggplot2 - ggplot2 geom_text 在饼图中的位置
- java - 如何排除某些依赖项被添加到 Maven 中的 Class-Path?
- dask - GPU Dask Cuda 集群:client.submit
- scala - 将 prepareStament 对象转换为 Json Scala
- r - 将 R 版本升级到 3.6 破坏了 Shiny 服务器库的访问
- java - Ren'py 启动器:“找不到 Java SE 运行时环境”