Skip to content

Commit b879ec8

Browse files
ydemartinomp911de
authored andcommitted
DATAMONGO-2596 - Introduce extension to render KProperty/KPropertyPath as property path.
Original pull request: #880.
1 parent c0581c4 commit b879ec8

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/query/KPropertyPath.kt

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,17 @@ import kotlin.reflect.KProperty1
2222
* Abstraction of a property path consisting of [KProperty].
2323
* @author Tjeu Kayim
2424
* @author Mark Paluch
25+
* @author Yoann de Martino
2526
* @since 2.2
2627
*/
2728
class KPropertyPath<T, U>(
2829
internal val parent: KProperty<U>,
2930
internal val child: KProperty1<U, T>
30-
) : KProperty<T> by child
31+
) : KProperty<T> by child {
32+
override fun toString(): String {
33+
return asString(this)
34+
}
35+
}
3136

3237
/**
3338
* Recursively construct field name for a nested property.
@@ -45,7 +50,7 @@ internal fun asString(property: KProperty<*>): String {
4550
* Builds [KPropertyPath] from Property References.
4651
* Refer to a field in an embedded/nested document.
4752
*
48-
* For example, referring to the field "book.author":
53+
* For example, referring to the field "author.name":
4954
* ```
5055
* Book::author / Author::name isEqualTo "Herman Melville"
5156
* ```

spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/query/KPropertyPathTests.kt

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import org.junit.Test
2020

2121
/**
2222
* @author Tjeu Kayim
23+
* @author Yoann de Martino
2324
*/
2425
class KPropertyPathTests {
2526

@@ -60,6 +61,26 @@ class KPropertyPathTests {
6061
assertThat(property).isEqualTo("entity.book.author.name")
6162
}
6263

64+
@Test
65+
fun `Convert nested KProperty to field name using toString()`() {
66+
67+
val property = (Book::author / Author::name).toString()
68+
69+
assertThat(property).isEqualTo("author.name")
70+
}
71+
72+
73+
@Test
74+
fun `Convert triple nested KProperty to field name using toString()`() {
75+
76+
class Entity(val book: Book)
77+
class AnotherEntity(val entity: Entity)
78+
79+
val property = (AnotherEntity::entity / Entity::book / Book::author / Author::name).toString()
80+
81+
assertThat(property).isEqualTo("entity.book.author.name")
82+
}
83+
6384
class Book(val title: String, val author: Author)
6485
class Author(val name: String)
6586
}

0 commit comments

Comments
 (0)