使用Kotlin和spring数据mongodb,我试图找到可以接收可空参数(通过用户定义的过滤器)的最惯用的方法,并使用非空参数创建MongoTemplate查询(在Java中是一堆ifs)。到目前为止,这是我想到的,但是我想知道是否有更好的方法:
// extending Query
open class Filter {
// case insensitive 'like' criteria
fun Query.like(field: String, value: String?) = value?.let {
this.addCriteria(Criteria.where(field).regex(it,"i"))
}
// queries from a date, to a date or between two dates
fun <T: Comparable<T>> Query.between(field: String, from: T?, to: T?) {
if (from != null || to != null) {
val criteria = where(field)
from?.let { criteria.gte(it) }
to?.let { criteria.lte(it) }
this.addCriteria(criteria)
}
}
fun Query.onlyActive(active: Boolean?) = when (active) {
true -> this.addCriteria(Criteria.where("active").`is`(true))
else -> null
}
}
// data class extending Filter()
data class myFilter(val: name: String, val type: String?, val content:String?,
val fromNum: Int?, val toNum: Int?, val fromDate: LocalDateTime?,
val toDate: LocalDateTime?, val active? = false): Filter() {
fun toQuery(): Query {
// name is a mandatory param
val query = Query.query(Criteria.where("name").`is`(name))
with(query) {
like("type", type)
like("content", content)
between("num", fromNum, toNum)
between("date", fromDate, toDate)
onlyActive(active)
}
return query
}
}