Created
November 22, 2018 10:11
-
-
Save TjeuKayim/91f52ae21bd5c33b99de028383d5ed89 to your computer and use it in GitHub Desktop.
Spring Mongo Typed Queries Experiment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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