在我们的Spring项目中,我希望将Java存储库转换为Kotlin。存储库是一个包含方法和注释的接口,其中包含作为参数的数据库查询。有几种方法,但是查询中最复杂和最长的部分是重复的。在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>
}谢谢
发布于 2021-10-12 15:20:01
您可以尝试使用同伴对象,如下所示:
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://stackoverflow.com/questions/69542012
复制相似问题