Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: add proper backwards-compatible Kotlin support #42

Merged
merged 2 commits into from
Sep 15, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions infobip-spring-data-common/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,14 @@
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-relational</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
<optional>true</optional>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PS I suspect that this can't be optional due to the fact that kotlin discovery code path is invoked every time, even in non kotlin environments?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In Spring Data Common it's optional, I think because we first invoke KotlinReflectionUtils. isSupportedKotlinClass from Spring, which - I think - doesn't rely on kotkin-reflect itself.

</dependency>
lpandzic marked this conversation as resolved.
Show resolved Hide resolved
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
lpandzic marked this conversation as resolved.
Show resolved Hide resolved
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package com.infobip.spring.data.common;

import kotlin.jvm.JvmClassMappingKt;
import kotlin.reflect.KFunction;
import kotlin.reflect.full.KClasses;
import kotlin.reflect.jvm.ReflectJvmMapping;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.mapping.PersistentEntity;
import org.springframework.data.mapping.PersistentProperty;
import org.springframework.data.mapping.PreferredConstructor;
import org.springframework.data.util.ClassTypeInformation;
import org.springframework.data.util.KotlinReflectionUtils;
import org.springframework.data.util.TypeInformation;
import org.springframework.lang.Nullable;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.util.*;

/**
* Utility class to find the preferred constructor which is compatible with both Spring Data JDBC and QueryDSL.
*/
interface PreferredConstructorDiscoverer {

@Nullable
static <T, P extends PersistentProperty<P>> PreferredConstructor<T, P> discover(Class<T> type) {
return Discoverers.findDiscoverer(type)
.discover(ClassTypeInformation.from(type), null);
}

enum Discoverers {

DEFAULT {

@Nullable
@Override
<T, P extends PersistentProperty<P>> PreferredConstructor<T, P> discover(
TypeInformation<T> type, @Nullable PersistentEntity<T, P> entity) {

return Arrays.stream(type.getType().getDeclaredConstructors())
.filter(it -> !it.isSynthetic())
.filter(it -> it.isAnnotationPresent(PersistenceConstructor.class))
.map(it -> buildPreferredConstructor(it, type, entity))
.findFirst()
.orElseGet(() -> Arrays.stream(type.getType().getDeclaredConstructors())
.filter(it -> !it.isSynthetic())
.max(Comparator.comparingInt(Constructor::getParameterCount))
.map(it -> buildPreferredConstructor(it, type, entity))
.orElse(null));
}
},

KOTLIN {

@Nullable
@Override
<T, P extends PersistentProperty<P>> PreferredConstructor<T, P> discover(
TypeInformation<T> type, @Nullable PersistentEntity<T, P> entity) {

return Arrays.stream(type.getType().getDeclaredConstructors())
.filter(it -> !it.isSynthetic())
.filter(it -> it.isAnnotationPresent(PersistenceConstructor.class))
.map(it -> buildPreferredConstructor(it, type, entity))
.findFirst()
.orElseGet(() -> {
KFunction<T> primaryConstructor = KClasses
.getPrimaryConstructor(JvmClassMappingKt.getKotlinClass(type.getType()));

if (primaryConstructor == null) {
return DEFAULT.discover(type, entity);
}

Constructor<T> javaConstructor = ReflectJvmMapping.getJavaConstructor(primaryConstructor);

return javaConstructor != null ? buildPreferredConstructor(javaConstructor, type, entity) : null;
});
}
};

private static final ParameterNameDiscoverer PARAMETER_NAME_DISCOVERER = new DefaultParameterNameDiscoverer();

private static Discoverers findDiscoverer(Class<?> type) {
return KotlinReflectionUtils.isSupportedKotlinClass(type) ? KOTLIN : DEFAULT;
}

@Nullable
abstract <T, P extends PersistentProperty<P>> PreferredConstructor<T, P> discover(TypeInformation<T> type,
@Nullable PersistentEntity<T, P> entity);

@SuppressWarnings({ "unchecked", "rawtypes" })
private static <T, P extends PersistentProperty<P>> PreferredConstructor<T, P> buildPreferredConstructor(
Constructor<?> constructor, TypeInformation<T> typeInformation, @Nullable PersistentEntity<T, P> entity) {

if (constructor.getParameterCount() == 0) {
return new PreferredConstructor<>((Constructor<T>) constructor);
}

List<TypeInformation<?>> parameterTypes = typeInformation.getParameterTypes(constructor);
String[] parameterNames = PARAMETER_NAME_DISCOVERER.getParameterNames(constructor);

PreferredConstructor.Parameter<Object, P>[] parameters = new PreferredConstructor.Parameter[parameterTypes.size()];
Annotation[][] parameterAnnotations = constructor.getParameterAnnotations();

for (int i = 0; i < parameterTypes.size(); i++) {

String name = parameterNames == null || parameterNames.length <= i ? null : parameterNames[i];
TypeInformation<?> type = parameterTypes.get(i);
Annotation[] annotations = parameterAnnotations[i];

parameters[i] = new PreferredConstructor.Parameter(name, type, annotations, entity);
}

return new PreferredConstructor<>((Constructor<T>) constructor, parameters);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import com.querydsl.sql.RelationalPathBase;
import org.springframework.core.ResolvableType;
import org.springframework.data.mapping.PreferredConstructor;
import org.springframework.data.mapping.model.PreferredConstructorDiscoverer;
import org.springframework.data.relational.core.mapping.Embedded;
import org.springframework.util.ReflectionUtils;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package com.infobip.spring.data.common

import org.assertj.core.api.BDDAssertions.then
import org.junit.jupiter.api.Test
import org.springframework.data.annotation.Id
import org.springframework.data.annotation.PersistenceConstructor
import org.springframework.data.mapping.PersistentProperty

class PreferredConstructorTest {

@Test
internal fun `it should prefer persistence constructors`() {
val preferredConstructor = PreferredConstructorDiscoverer
.discover<EntityWithPersistenceConstructor, PersistentProperty<*>>(EntityWithPersistenceConstructor::class.java)

then(preferredConstructor.parameters).hasSize(3)
then(preferredConstructor.parameters.map { it.name }).containsExactly("id", "firstName", "lastName")
}

@Test
internal fun `if no persistence constructor, it should take primary constructor`() {
val preferredConstructor = PreferredConstructorDiscoverer
.discover<DataClass, PersistentProperty<*>>(DataClass::class.java)

then(preferredConstructor.parameters).hasSize(3)
then(preferredConstructor.parameters.map { it.name }).containsExactly("id", "firstName", "lastName")
}

@Test
internal fun `if no primary constructor, it should take constructor with most arguments`() {
val preferredConstructor = PreferredConstructorDiscoverer
.discover<EntityWithoutPersistenceConstructor, PersistentProperty<*>>(EntityWithoutPersistenceConstructor::class.java)

then(preferredConstructor.parameters).hasSize(3)
then(preferredConstructor.parameters.map { it.name }).containsExactly("id", "firstName", "lastName")
}
}

data class DataClass(
@Id private val id: String,
val firstName: String,
val lastName: String
)

data class EntityWithPersistenceConstructor(
@Id private val id: String,
private val nameInformation: NameInformation
) {
@PersistenceConstructor
constructor(id: String, firstName: String, lastName: String): this(id, NameInformation(firstName, lastName))
}

class EntityWithoutPersistenceConstructor {
val id: String
val nameInformation: NameInformation

constructor() {
this.id = "_"
this.nameInformation = NameInformation("_", "_")
}

constructor(id: String, firstName: String, lastName: String) {
this.id = id
this.nameInformation = NameInformation(firstName, lastName)
}
}

data class NameInformation(val firstName: String, val lastName: String)
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ public class NoArgsEntity {
this.value = null;
}

@PersistenceConstructor
lpandzic marked this conversation as resolved.
Show resolved Hide resolved
public NoArgsEntity(Long id, String value) {
this.id = id;
this.value = value;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ void shouldBeAbleToJoin() {
}

@Test
void shouldSupportMultipleConstructors() {
void shouldSupportMultipleConstructorsWithEntityProjection() {
// given
NoArgsEntity givenNoArgsEntity = giveNoArgsEntity();

Expand All @@ -218,6 +218,21 @@ void shouldSupportMultipleConstructors() {
then(actual).containsExactly(givenNoArgsEntity);
}

@Test
void shouldSupportMultipleConstructors() {
// given
NoArgsEntity givenNoArgsEntity = giveNoArgsEntity();

// when
List<NoArgsEntity> actual = noArgsRepository.query(query -> query
.select(QNoArgsEntity.noArgsEntity)
.from(QNoArgsEntity.noArgsEntity)
.limit(1)
.fetch());

then(actual).containsExactly(givenNoArgsEntity);
}

@Test
void shouldExtendSimpleQuerydslJdbcRepository() {
// then
Expand Down
54 changes: 54 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@
<!-- OTHER PROPERTIES -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>

<kotlin.version>1.5.30</kotlin.version>
</properties>

<dependencyManagement>
Expand Down Expand Up @@ -159,6 +161,11 @@
<version>${infobip-mssql-testcontainers.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>

<build>
Expand All @@ -185,10 +192,57 @@
</plugins>
</pluginManagement>
<plugins>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<configuration>
<jvmTarget>1.8</jvmTarget>
</configuration>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>

<executions>
<execution>
<id>test-compile</id>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/test/java</sourceDir>
<sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<executions>
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
<execution>
<id>default-testCompile</id>
<phase>none</phase>
</execution>
<execution>
<id>java-compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>java-test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
Expand Down