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

#101: Add support for collection constructor creation #3108

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
d6425e0
#101: Add support for collection constructor creation
epochcoder Mar 8, 2024
be7650e
#101: Compatibility with java 11, and remove star imports
epochcoder Mar 8, 2024
75a2e58
#101: Add test with multiple nested levels of mapping
epochcoder Mar 8, 2024
5061ca0
#101: Simplify main result handling loop and completely hide new func…
epochcoder Mar 8, 2024
05527aa
#101: Completely isolate new behaviour from existing via flag
epochcoder Mar 9, 2024
c48c238
#101: Specify max size for pending creations
epochcoder Mar 9, 2024
204a09c
#101: Remove unrelated formatting
epochcoder Mar 9, 2024
a54582b
#101: Add test with an association constructor argument
epochcoder Mar 9, 2024
153ad19
Merge branch 'mybatis:master' into feature/101-support-constructor-co…
epochcoder Mar 12, 2024
5be1b0c
#101: Add usage documentation
epochcoder Mar 12, 2024
f9dfb6b
#101: Drastically improve performance by only checking if we can crea…
epochcoder Mar 18, 2024
f487eab
#101: Update testing by adding a large data load with a comparison be…
epochcoder Mar 18, 2024
0c52fa4
#101: Don't insert performance data on CI
epochcoder Mar 18, 2024
70dfaa9
#101 Remove disabled performance test and data
Mar 20, 2024
d5e0167
#101 Do not calculate flag everywhere, do it only once while building…
Mar 21, 2024
1957e6a
#101 Remove unneeded flag calculation
Mar 21, 2024
c564187
#101 Ensure we check that nestedQueryId is null for the flag
Mar 21, 2024
7d36682
Merge branch 'master' into feature/101-support-constructor-collection…
epochcoder May 24, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions pom.xml
Expand Up @@ -104,6 +104,10 @@
<name>Tomáš Neuberg</name>
<email>neuberg@m-atelier.cz</email>
</contributor>
<contributor>
<name>Willie Scholtz</name>
<email>williescholtz@gmail.com</email>
</contributor>
</contributors>

<scm>
Expand Down
@@ -1,5 +1,5 @@
/*
* Copyright 2009-2023 the original author or authors.
* Copyright 2009-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -293,6 +293,8 @@ private void settingsElement(Properties props) {
booleanValueOf(props.getProperty("argNameBasedConstructorAutoMapping"), false));
configuration.setDefaultSqlProviderType(resolveClass(props.getProperty("defaultSqlProviderType")));
configuration.setNullableOnForEach(booleanValueOf(props.getProperty("nullableOnForEach"), false));
configuration.setExperimentalConstructorCollectionMapping(
booleanValueOf(props.getProperty("experimentalConstructorCollectionMapping"), false));
}

private void environmentsElement(XNode context) throws Exception {
Expand Down

Large diffs are not rendered by default.

@@ -0,0 +1,213 @@
/*
* Copyright 2009-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.executor.resultset;

import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.reflection.ReflectionException;
import org.apache.ibatis.reflection.factory.ObjectFactory;

/**
* Represents an object that is still to be created once all nested results with collection values have been gathered
*
* @author Willie Scholtz
*/
final class PendingConstructorCreation {
private final Class<?> resultType;
private final List<Class<?>> constructorArgTypes;
private final List<Object> constructorArgs;
private final Map<Integer, PendingCreationMetaInfo> linkedCollectionMetaInfo;
private final Map<String, Collection<Object>> linkedCollectionsByResultMapId;
private final Map<String, List<PendingConstructorCreation>> linkedCreationsByResultMapId;

PendingConstructorCreation(Class<?> resultType, List<Class<?>> types, List<Object> args) {
// since all our keys are based on result map id, we know we will never go over args size
final int maxSize = types.size();
this.linkedCollectionMetaInfo = new HashMap<>(maxSize);
this.linkedCollectionsByResultMapId = new HashMap<>(maxSize);
this.linkedCreationsByResultMapId = new HashMap<>(maxSize);
this.resultType = resultType;
this.constructorArgTypes = types;
this.constructorArgs = args;
}

@SuppressWarnings("unchecked")
Collection<Object> initializeCollectionForResultMapping(ObjectFactory objectFactory, ResultMap resultMap,
ResultMapping constructorMapping, Integer index) {
final Class<?> parameterType = constructorMapping.getJavaType();
if (!objectFactory.isCollection(parameterType)) {
throw new ExecutorException(
"Cannot add a collection result to non-collection based resultMapping: " + constructorMapping);
}

final String resultMapId = constructorMapping.getNestedResultMapId();
return linkedCollectionsByResultMapId.computeIfAbsent(resultMapId, (k) -> {
// this will allow us to verify the types of the collection before creating the final object
linkedCollectionMetaInfo.put(index, new PendingCreationMetaInfo(resultMap.getType(), resultMapId));

// will be checked before we finally create the object) as we cannot reliably do that here
return (Collection<Object>) objectFactory.create(parameterType);
});
}

void linkCreation(ResultMap nestedResultMap, PendingConstructorCreation pcc) {
final String resultMapId = nestedResultMap.getId();
final List<PendingConstructorCreation> pendingConstructorCreations = linkedCreationsByResultMapId
.computeIfAbsent(resultMapId, (k) -> new ArrayList<>());

if (pendingConstructorCreations.contains(pcc)) {
throw new ExecutorException("Cannot link inner pcc with same value, MyBatis programming error!");
}

pendingConstructorCreations.add(pcc);
}

void linkCollectionValue(ResultMapping constructorMapping, Object value) {
// not necessary to add null results to the collection (is this a config flag?)
if (value == null) {
return;
}

final String resultMapId = constructorMapping.getNestedResultMapId();
if (!linkedCollectionsByResultMapId.containsKey(resultMapId)) {
throw new ExecutorException("Cannot link collection value for resultMapping: " + constructorMapping
+ ", resultMap has not been seen/initialized yet! Internal error");
}

linkedCollectionsByResultMapId.get(resultMapId).add(value);
}

/**
* Verifies preconditions before we can actually create the result object, this is more of a sanity check to ensure
* all the mappings are as we expect them to be.
*
* @param objectFactory
* the object factory
*/
private void verifyCanCreate(ObjectFactory objectFactory) {
// before we create, we need to get the constructor to be used and verify our types match
// since we added to the collection completely unchecked
final Constructor<?> resolvedConstructor = objectFactory.resolveConstructor(resultType, constructorArgTypes);
final Type[] genericParameterTypes = resolvedConstructor.getGenericParameterTypes();
for (int i = 0; i < genericParameterTypes.length; i++) {
if (!linkedCollectionMetaInfo.containsKey(i)) {
continue;
}

final PendingCreationMetaInfo creationMetaInfo = linkedCollectionMetaInfo.get(i);
final Class<?> resolvedItemType = checkResolvedItemType(creationMetaInfo, genericParameterTypes[i]);

// ensure we have an empty collection if there are linked creations for this arg
final String resultMapId = creationMetaInfo.getResultMapId();
if (linkedCreationsByResultMapId.containsKey(resultMapId)) {
final Object emptyCollection = constructorArgs.get(i);
if (emptyCollection == null || !objectFactory.isCollection(emptyCollection.getClass())) {
throw new ExecutorException(
"Expected empty collection for '" + resolvedItemType + "', this is a MyBatis internal error!");
}
} else {
final Object linkedCollection = constructorArgs.get(i);
if (!linkedCollectionsByResultMapId.containsKey(resultMapId)) {
throw new ExecutorException("Expected linked collection for resultMap '" + resultMapId
+ "', not found! this is a MyBatis internal error!");
}

// comparing memory locations here (we rely on that fact)
if (linkedCollection != linkedCollectionsByResultMapId.get(resultMapId)) {
throw new ExecutorException("Expected linked collection in creation to be the same as arg for resultMap '"
+ resultMapId + "', not equal! this is a MyBatis internal error!");
}
}
}
}

private static Class<?> checkResolvedItemType(PendingCreationMetaInfo creationMetaInfo, Type genericParameterTypes) {
final ParameterizedType genericParameterType = (ParameterizedType) genericParameterTypes;
final Class<?> expectedType = (Class<?>) genericParameterType.getActualTypeArguments()[0];
final Class<?> resolvedItemType = creationMetaInfo.getArgumentType();

if (!expectedType.isAssignableFrom(resolvedItemType)) {
throw new ReflectionException(
"Expected type '" + resolvedItemType + "', while the actual type of the collection was '" + expectedType
+ "', ensure your resultMap matches the type of the collection you are trying to inject");
}

return resolvedItemType;
}

@Override
public String toString() {
return "PendingConstructorCreation(" + this.hashCode() + "){" + "resultType=" + resultType + '}';
}

/**
* Recursively creates the final result of this creation.
*
* @param objectFactory
* the object factory
* @param verifyCreate
* should we verify this object can be created, should only be needed once
*
* @return the new immutable result
*/
Object create(ObjectFactory objectFactory, boolean verifyCreate) {
if (verifyCreate) {
verifyCanCreate(objectFactory);
}

final List<Object> newArguments = new ArrayList<>(constructorArgs.size());
for (int i = 0; i < constructorArgs.size(); i++) {
final PendingCreationMetaInfo creationMetaInfo = linkedCollectionMetaInfo.get(i);
final Object existingArg = constructorArgs.get(i);

if (creationMetaInfo == null) {
// we are not aware of this argument wrt pending creations
newArguments.add(existingArg);
continue;
}

// time to finally build this collection
final String resultMapId = creationMetaInfo.getResultMapId();
if (linkedCreationsByResultMapId.containsKey(resultMapId)) {
@SuppressWarnings("unchecked")
final Collection<Object> emptyCollection = (Collection<Object>) existingArg;
final List<PendingConstructorCreation> linkedCreations = linkedCreationsByResultMapId.get(resultMapId);

for (PendingConstructorCreation linkedCreation : linkedCreations) {
emptyCollection.add(linkedCreation.create(objectFactory, verifyCreate));
}

newArguments.add(emptyCollection);
continue;
}

// handle the base collection (it was built inline already)
newArguments.add(existingArg);
}

return objectFactory.create(resultType, constructorArgTypes, newArguments);
}
}
@@ -0,0 +1,42 @@
/*
* Copyright 2009-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.executor.resultset;

/**
* @author Willie Scholtz
*/
final class PendingCreationMetaInfo {
private final Class<?> argumentType;
private final String resultMapId;

PendingCreationMetaInfo(Class<?> argumentType, String resultMapId) {
this.argumentType = argumentType;
this.resultMapId = resultMapId;
}

Class<?> getArgumentType() {
return argumentType;
}

String getResultMapId() {
return resultMapId;
}

@Override
public String toString() {
return "PendingCreationMetaInfo{" + "argumentType=" + argumentType + ", resultMapId='" + resultMapId + '\'' + '}';
}
}
16 changes: 15 additions & 1 deletion src/main/java/org/apache/ibatis/mapping/ResultMap.java
@@ -1,5 +1,5 @@
/*
* Copyright 2009-2023 the original author or authors.
* Copyright 2009-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -46,6 +46,7 @@ public class ResultMap {
private Set<String> mappedColumns;
private Set<String> mappedProperties;
private Discriminator discriminator;
private boolean hasResultMapsUsingConstructorCollection;
private boolean hasNestedResultMaps;
private boolean hasNestedQueries;
private Boolean autoMapping;
Expand Down Expand Up @@ -111,6 +112,15 @@ public ResultMap build() {
}
if (resultMapping.getFlags().contains(ResultFlag.CONSTRUCTOR)) {
resultMap.constructorResultMappings.add(resultMapping);

//#101
if (resultMap.configuration.isExperimentalConstructorCollectionMappingEnabled()) {
Class<?> javaType = resultMapping.getJavaType();
resultMap.hasResultMapsUsingConstructorCollection = resultMap.hasResultMapsUsingConstructorCollection
|| (resultMapping.getNestedQueryId() == null
&& javaType != null && resultMap.configuration.getObjectFactory().isCollection(javaType));
}

if (resultMapping.getProperty() != null) {
constructorArgNames.add(resultMapping.getProperty());
}
Expand Down Expand Up @@ -210,6 +220,10 @@ public String getId() {
return id;
}

public boolean hasResultMapsUsingConstructorCollection() {
return hasResultMapsUsingConstructorCollection;
}

public boolean hasNestedResultMaps() {
return hasNestedResultMaps;
}
Expand Down
@@ -1,5 +1,5 @@
/*
* Copyright 2009-2023 the original author or authors.
* Copyright 2009-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -53,6 +53,22 @@ public <T> T create(Class<T> type, List<Class<?>> constructorArgTypes, List<Obje
return (T) instantiateClass(classToCreate, constructorArgTypes, constructorArgs);
}

@Override
public <T> Constructor<T> resolveConstructor(Class<T> type, List<Class<?>> constructorArgTypes) {
try {
if (constructorArgTypes == null) {
return type.getDeclaredConstructor();
}

return type.getDeclaredConstructor(constructorArgTypes.toArray(new Class[0]));
} catch (Exception e) {
String argTypes = Optional.ofNullable(constructorArgTypes).orElseGet(Collections::emptyList).stream()
.map(Class::getSimpleName).collect(Collectors.joining(","));
throw new ReflectionException(
"Error resolving constructor for " + type + " with invalid types (" + argTypes + ") . Cause: " + e, e);
}
}

private <T> T instantiateClass(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
try {
Constructor<T> constructor;
Expand Down
@@ -1,5 +1,5 @@
/*
* Copyright 2009-2023 the original author or authors.
* Copyright 2009-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -15,6 +15,7 @@
*/
package org.apache.ibatis.reflection.factory;

import java.lang.reflect.Constructor;
import java.util.List;
import java.util.Properties;

Expand Down Expand Up @@ -63,6 +64,20 @@ default void setProperties(Properties properties) {
*/
<T> T create(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs);

/**
* Resolves the constructor for the type and argument types.
*
* @param <T>
* the generic type
* @param type
* Object type
* @param constructorArgTypes
* Constructor argument types
*
* @return the t
*/
<T> Constructor<T> resolveConstructor(Class<T> type, List<Class<?>> constructorArgTypes);

/**
* Returns true if this object can have a set of other objects. It's main purpose is to support
* non-java.util.Collection objects like Scala collections.
Expand Down