【问题标题】:Spring data, derived repository methodSpring数据,派生存储库方法
【发布时间】:2020-02-23 19:09:55
【问题描述】:

我有一个工作的 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] o.s.d.m.r.query.MongoQueryCreator :创建查询查询:{ “类型”:{“$java”:官方}},字段:{},排序:{} 2019-10-28 14:44:25.165 错误 2986 --- [ctor-http-nio-4] a.w.r.e.AbstractErrorWebExceptionHandler:[a29dfc95] 500 服务器错误 对于 HTTP GET "/api/user/news/pages"

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

我猜这与 ReactiveMongoRepository 签名&lt;News, String&gt;有关

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

【问题讨论】:

  • 由于这是一个响应式存储库,请尝试将您的 Long 返回类型更改为 Mono&lt;Long&gt;
  • 我试过了,但它只是打印“MonoOnErrorResume”

标签: mongodb kotlin spring-data-jpa


【解决方案1】:

看起来在 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())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-31
    • 2020-06-17
    • 2016-07-02
    • 2015-10-26
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 2011-05-06
    相关资源
    最近更新 更多