【发布时间】:2019-12-31 19:10:40
【问题描述】:
我是 Kotlin 和 JPA 的新手。我有一个从两个表(Postgres)获取数据的内部连接查询。查询工作正常。但是,由于我现在有两种类型(两张表),因此使用其中一种只会返回其中一张表中的所有字段。为了返回所有字段,我将类型更改为 List。但是,当我这样做时,我返回的对象没有字段,只有原始数据。如何更改我的代码,以便我的 json 响应包含字段名称和数据。
对不起,如果我的问题不清楚,我对 Kotlin 很陌生。
更新的代码 我的存储库代码
package com.sg.xxx.XXXTTT.report.repository
import com.sg.xxx.XXXTTT.report.model.Report
import com.sg.xxx.XXXTTT.report.model.ReportWithBatches
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.stereotype.Repository
import java.time.LocalDate
@Repository
interface IReportRepository : JpaRepository<Report, Long> {
fun findAllByCreationDate(date: LocalDate): List<Report>
fun findByReportName(name: String): Report?
fun findByAdlsFullPath(name: String): Report?
@Query("SELECT new com.sg.xxx.xxxttt.report.model.ReportWithBatches(r.adlsFullPath, r.sentToXXX, r.contentLength, r.creationDate, r.remoteFileNameOnFTA, b.dataPath , b.version, b.source, r.numberOfRecords) FROM Report r INNER JOIN BatchInfo b ON r.reportUuid = b.reportUuid WHERE r.creationDate = ?1")
fun findAllByCreationDateJoinBatches(date: LocalDate): List<ReportWithBatches>
}
我的控制器代码
@GetMapping(value = ["/linkBatches/{today}"])
fun findAllByCreationDateJoinBatches(@PathVariable("today") @DateTimeFormat(pattern = "yyyyMMdd") date: LocalDate): List<ReportWithBatches> {
return eligibleService.findAllByCreationDateJoinBatches(date)
}
我的 DTO
package com.sg.xxx.xxxttt.report.model
import java.time.LocalDate
open class ReportWithBatches(
var adlsFullPath: String?,
var sentToXXX: Boolean?,
var contentLength: Long?,
var creationDate: LocalDate,
var remoteFileNameOnFTA: String?,
var dataPath: String?,
var version: Int?,
var source: String?,
var numberOfRecords: Long?
)
我在服务中的功能
fun findAllByCreationDateJoinBatches(date: LocalDate): List<ReportWithBatches> {
return reportRepository.findAllByCreationDateJoinBatches(date)
}
}
【问题讨论】:
-
不要使用本机查询。学习 JPQL。以下是 JPQL 中有关联接的文档:docs.jboss.org/hibernate/orm/current/userguide/html_single/…。此外,在返回 JSON 的控制器和返回数据的查询之间,您可以并且应该编写将数据转换为所需对象的代码,以便发回所需的 JSON。 Yoru 查询实际上返回一个 List
>,您可以将这个列表转换为您想要的任何内容。
标签: spring jpa kotlin spring-data-jpa