Skip to content

Type-safe Kotlin query extension like mongo template #1937

Closed as not planned
Closed as not planned
@jurogrammer

Description

@jurogrammer

I would like to perform type-safe queries using R2dbcTemplate. My goal is to achieve functionality similar to MongoDB's template, as you suggested—reference test code.

However, there’s an issue with handling column names, as described in this issue. I’m considering a default strategy for resolving column names, though this might limit the flexibility of custom column name strategies, similar to MongoDB’s template, which only considers property names.

Are there any considerations I should keep in mind?

extension

import org.springframework.data.relational.core.query.Criteria
import org.springframework.data.relational.core.query.Criteria.CriteriaStep
import org.springframework.data.util.ParsingUtils
import kotlin.reflect.KProperty


fun where(key: KProperty<*>): CriteriaStep = Criteria.where(key.toColumn())
internal fun KProperty<*>.toColumn(): String = ParsingUtils.reconcatenateCamelCase(this.name, "_")

test

Since CriteriaBuilder doesn't override equals, I'm using toString for comparison.

import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.data.relational.core.query.Criteria

class CriteriaExtensionsKtTest {

    @Test
    fun `where(KProperty) should equal Criteria where()`() {
        val typedCriteria = where(Customer::firstName).`is`("John").toString()
        val classicCriteria = Criteria.where("first_name").`is`("John").toString()

        assertThat(typedCriteria).isEqualTo(classicCriteria)
    }


    class Customer(val firstName: String, val lastName: String)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions