在我們的 Spring 專案中,我想將 Java 存盤庫轉換為 Kotlin。Repository 是一個帶有方法和注釋的介面,其中包含資料庫查詢作為引數。有幾種方法,但重復查詢中最復雜和最長的部分。在 Java 中,我們將一個字串作為變數插入到查詢中。
Kotlin 中的當前解決方案無法編譯,因為“注釋引數必須是編譯時常量”。
處理這個問題的最佳方法是什么?
interface PlaceRepository : JpaRepository<Place, UUID>, JpaSpecificationExecutor<Place> {
val HAVERSINE_FORMULA: String
get() =
"""
(6371 * acos(cos(radians(CAST(CAST(:latitude AS string) AS double)))
* cos(radians(p.gpsLatitude)) * cos(radians(p.gpsLongitude) - radians(CAST(CAST(:longitude AS string) AS double)))
sin(radians(CAST(CAST(:latitude AS string) AS double))) * sin(radians(p.gpsLatitude))))
"""
@Query("""
SELECT p AS place,
$HAVERSINE_FORMULA AS distance
FROM Place p
WHERE p.code = :code
""")
fun findByCode(
code: String,
latitude: Double,
longitude: Double
): Optional<PlaceWithDistanceDTO>
}
謝謝
uj5u.com熱心網友回復:
您可以嘗試使用伴隨物件,如下所示:
interface PlaceRepository : JpaRepository<Place, UUID>, JpaSpecificationExecutor<Place> {
companion object {
private const val HAVERSINE_FORMULA =
"""
(6371 * acos(cos(radians(CAST(CAST(:latitude AS string) AS double)))
* cos(radians(p.gpsLatitude)) * cos(radians(p.gpsLongitude) - radians(CAST(CAST(:longitude AS string) AS double)))
sin(radians(CAST(CAST(:latitude AS string) AS double))) * sin(radians(p.gpsLatitude))))
"""
}
@Query("""
SELECT p AS place,
$HAVERSINE_FORMULA AS distance
FROM Place p
WHERE p.code = :code
""")
fun findByCode(
code: String,
latitude: Double,
longitude: Double
): Optional<PlaceWithDistanceDTO>
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/312856.html
