spring
[spring data mongo] Query를 Type-safe 하게 작성하기 (작성 중)
돼지발자
2024. 11. 19. 12:24
728x90
spring data mongo를 사용하여 MongoTemplate 를 이용하여 쿼리를 작성하다 보면 아래와 같이 필드값에 대해 string 값을 사용하게 된다.
Criteria.where("_id").`is`(Entity.id)
하지만 이렇게 쿼리를 사용하다 보면 type-safe 하지 않다는 점과 실제로 해당 엔티티에 존재하는 필드인지 오탈자는 없는지 실행되는 순간까지 확인할 수 없으므로 위험도는 증가한다.
private class KPropertyPath<T, U>(
val parent: KProperty<U?>,
val child: KProperty1<U, T>
) : KProperty<T> by child
/**
* Recursively construct field name for a nested property.
* @author Tjeu Kayim
*/
internal fun asString(property: KProperty<*>): String {
return when (property) {
is KPropertyPath<*, *> ->
"${asString(property.parent)}.${property.child.name}"
else -> property.name
}
}
/**
* Builds [KPropertyPath] from Property References.
* Refer to a nested property in an embeddable or association.
*
* For example, referring to the field "author.name":
* ```
* Book::author / Author::name isEqualTo "Herman Melville"
* ```
* @author Tjeu Kayim
* @author Yoann de Martino
* @since 2.5
*/
operator fun <T, U> KProperty<T?>.div(other: KProperty1<T, U>): KProperty<U> =
KPropertyPath(this, other)
728x90