Skip to content

Instantly share code, notes, and snippets.

@TjeuKayim
Created November 22, 2018 10:11
Show Gist options
  • Save TjeuKayim/91f52ae21bd5c33b99de028383d5ed89 to your computer and use it in GitHub Desktop.
Save TjeuKayim/91f52ae21bd5c33b99de028383d5ed89 to your computer and use it in GitHub Desktop.
Spring Mongo Typed Queries Experiment
package com.github.tjeukayim
import org.bson.types.ObjectId
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.springframework.data.mongodb.core.mapping.Document
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.CriteriaDefinition
import org.springframework.data.mongodb.core.query.isEqualTo
import kotlin.reflect.KProperty
class TypedQueriesTest {
@Test
fun `Typed query gt and isEqualTo`() {
val classic = Criteria("price").gt(1100)
.and("available").isEqualTo(true)
val typed = typedCriteria {
Book::price gt 1100
Book::available isEqualTo true
}
assertEquals(classic, typed)
}
}
@Document("books")
data class Book(
val id: ObjectId,
val name: String,
val price: Int,
val available: Boolean
)
fun typedCriteria(block: TypedCriteria.() -> Unit): CriteriaDefinition {
val builder = TypedCriteria()
builder.block()
return builder.chain
}
class TypedCriteria {
var chain = Criteria()
infix fun <T : Any> KProperty<T>.gt(value: T) {
chain = chain.and(name).gt(value)
}
infix fun <T : Any> KProperty<T>.isEqualTo(value: T) {
chain = chain.and(name).isEqualTo(value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment