From 8618782cc501adad6c16e92552c44627ed44954f Mon Sep 17 00:00:00 2001 From: Jeremy Landis Date: Sat, 4 Feb 2023 14:09:56 -0500 Subject: [PATCH] [ci] formatting --- .../mapping/VendorDatabaseIdProvider.java | 6 +- .../ibatis/reflection/SystemMetaObject.java | 8 +- .../reflection/TypeParameterResolver.java | 25 +- .../reflection/wrapper/BaseWrapper.java | 8 +- .../reflection/wrapper/BeanWrapper.java | 16 +- .../wrapper/DefaultObjectWrapperFactory.java | 5 +- .../ibatis/reflection/wrapper/MapWrapper.java | 5 +- .../ibatis/scripting/LanguageDriver.java | 44 +- .../scripting/defaults/RawLanguageDriver.java | 8 +- .../scripting/defaults/RawSqlSource.java | 6 +- .../scripting/xmltags/DynamicContext.java | 4 +- .../xmltags/ExpressionEvaluator.java | 9 +- .../scripting/xmltags/ForEachSqlNode.java | 17 +- .../scripting/xmltags/OgnlClassResolver.java | 7 +- .../scripting/xmltags/OgnlMemberAccess.java | 6 +- .../ibatis/scripting/xmltags/SetSqlNode.java | 4 +- .../ibatis/scripting/xmltags/TrimSqlNode.java | 11 +- .../scripting/xmltags/WhereSqlNode.java | 5 +- .../scripting/xmltags/XMLLanguageDriver.java | 5 +- .../scripting/xmltags/XMLScriptBuilder.java | 9 +- .../AutoMappingUnknownColumnBehavior.java | 45 +- .../apache/ibatis/session/Configuration.java | 91 ++- .../ibatis/session/LocalCacheScope.java | 4 +- .../org/apache/ibatis/session/SqlSession.java | 260 ++++-- .../session/SqlSessionFactoryBuilder.java | 14 +- .../ibatis/session/SqlSessionManager.java | 10 +- .../session/defaults/DefaultSqlSession.java | 10 +- .../defaults/DefaultSqlSessionFactory.java | 5 +- .../ibatis/builder/XmlMapperBuilderTest.java | 169 ++-- .../cursor/defaults/DefaultCursorTest.java | 22 +- .../exceptions/GeneralExceptionsTest.java | 28 +- .../ibatis/executor/ExecutorTestHelper.java | 769 +++++++++--------- .../DefaultResultSetHandlerTest.java | 15 +- .../DefaultResultSetHandlerTest2.java | 40 +- .../ibatis/mapping/ResultMappingTest.java | 15 +- .../defaults/DefaultParameterHandlerTest.java | 18 +- .../AutoMappingUnknownColumnBehaviorTest.java | 173 ++-- .../member_access/MemberAccessTest.java | 130 ++- .../InvalidNamedConstructorArgsTest.java | 21 +- .../named_constructor_args/Mapper.java | 6 +- .../UseActualNameMapper.java | 6 +- .../NoActualParamNameTest.java | 50 +- .../record_type/RecordTypeMapper.java | 10 +- .../repeatable/RepeatableErrorTest.java | 8 +- .../ibatis/submitted/results_id/Mapper.java | 18 +- .../ibatis/submitted/sptests/SPMapper.java | 37 +- .../ibatis/submitted/sptests/SPTest.java | 3 +- .../apache/ibatis/submitted/sql/Mapper.java | 16 +- .../ibatis/submitted/typehandler/Mapper.java | 26 +- 49 files changed, 1231 insertions(+), 996 deletions(-) diff --git a/src/main/java/org/apache/ibatis/mapping/VendorDatabaseIdProvider.java b/src/main/java/org/apache/ibatis/mapping/VendorDatabaseIdProvider.java index 756ab1e00a3..bccad8c9159 100644 --- a/src/main/java/org/apache/ibatis/mapping/VendorDatabaseIdProvider.java +++ b/src/main/java/org/apache/ibatis/mapping/VendorDatabaseIdProvider.java @@ -29,9 +29,9 @@ /** * Vendor DatabaseId provider. *

- * It returns database product name as a databaseId. If the user provides a properties it uses it to - * translate database product name key="Microsoft SQL Server", value="ms" will return "ms". It can return - * null, if no database product name or a properties was specified and no translation was found. + * It returns database product name as a databaseId. If the user provides a properties it uses it to translate database + * product name key="Microsoft SQL Server", value="ms" will return "ms". It can return null, if no database product name + * or a properties was specified and no translation was found. * * @author Eduardo Macarron */ diff --git a/src/main/java/org/apache/ibatis/reflection/SystemMetaObject.java b/src/main/java/org/apache/ibatis/reflection/SystemMetaObject.java index b98fb96bf05..671d82bf5cb 100644 --- a/src/main/java/org/apache/ibatis/reflection/SystemMetaObject.java +++ b/src/main/java/org/apache/ibatis/reflection/SystemMetaObject.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -27,7 +27,8 @@ public final class SystemMetaObject { public static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory(); public static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory(); - public static final MetaObject NULL_META_OBJECT = MetaObject.forObject(new NullObject(), DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY, new DefaultReflectorFactory()); + public static final MetaObject NULL_META_OBJECT = MetaObject.forObject(new NullObject(), DEFAULT_OBJECT_FACTORY, + DEFAULT_OBJECT_WRAPPER_FACTORY, new DefaultReflectorFactory()); private SystemMetaObject() { // Prevent Instantiation of Static Class @@ -37,7 +38,8 @@ private static class NullObject { } public static MetaObject forObject(Object object) { - return MetaObject.forObject(object, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY, new DefaultReflectorFactory()); + return MetaObject.forObject(object, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY, + new DefaultReflectorFactory()); } } diff --git a/src/main/java/org/apache/ibatis/reflection/TypeParameterResolver.java b/src/main/java/org/apache/ibatis/reflection/TypeParameterResolver.java index 9f2df476c93..87a48ff0eaf 100644 --- a/src/main/java/org/apache/ibatis/reflection/TypeParameterResolver.java +++ b/src/main/java/org/apache/ibatis/reflection/TypeParameterResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -37,6 +37,7 @@ public class TypeParameterResolver { * the field * @param srcType * the src type + * * @return The field type as {@link Type}. If it has type parameters in the declaration,
* they will be resolved to the actual runtime {@link Type}s. */ @@ -53,6 +54,7 @@ public static Type resolveFieldType(Field field, Type srcType) { * the method * @param srcType * the src type + * * @return The return type of the method as {@link Type}. If it has type parameters in the declaration,
* they will be resolved to the actual runtime {@link Type}s. */ @@ -69,6 +71,7 @@ public static Type resolveReturnType(Method method, Type srcType) { * the method * @param srcType * the src type + * * @return The parameter types of the method as an array of {@link Type}s. If they have type parameters in the * declaration,
* they will be resolved to the actual runtime {@link Type}s. @@ -95,7 +98,8 @@ private static Type resolveType(Type type, Type srcType, Class declaringClass } } - private static Type resolveGenericArrayType(GenericArrayType genericArrayType, Type srcType, Class declaringClass) { + private static Type resolveGenericArrayType(GenericArrayType genericArrayType, Type srcType, + Class declaringClass) { Type componentType = genericArrayType.getGenericComponentType(); Type resolvedComponentType = null; if (componentType instanceof TypeVariable) { @@ -112,7 +116,8 @@ private static Type resolveGenericArrayType(GenericArrayType genericArrayType, T } } - private static ParameterizedType resolveParameterizedType(ParameterizedType parameterizedType, Type srcType, Class declaringClass) { + private static ParameterizedType resolveParameterizedType(ParameterizedType parameterizedType, Type srcType, + Class declaringClass) { Class rawType = (Class) parameterizedType.getRawType(); Type[] typeArgs = parameterizedType.getActualTypeArguments(); Type[] args = new Type[typeArgs.length]; @@ -161,7 +166,8 @@ private static Type resolveTypeVar(TypeVariable typeVar, Type srcType, Class< ParameterizedType parameterizedType = (ParameterizedType) srcType; clazz = (Class) parameterizedType.getRawType(); } else { - throw new IllegalArgumentException("The 2nd arg must be Class or ParameterizedType, but was: " + srcType.getClass()); + throw new IllegalArgumentException( + "The 2nd arg must be Class or ParameterizedType, but was: " + srcType.getClass()); } if (clazz == declaringClass) { @@ -188,7 +194,8 @@ private static Type resolveTypeVar(TypeVariable typeVar, Type srcType, Class< return Object.class; } - private static Type scanSuperTypes(TypeVariable typeVar, Type srcType, Class declaringClass, Class clazz, Type superclass) { + private static Type scanSuperTypes(TypeVariable typeVar, Type srcType, Class declaringClass, Class clazz, + Type superclass) { if (superclass instanceof ParameterizedType) { ParameterizedType parentAsType = (ParameterizedType) superclass; Class parentAsClass = (Class) parentAsType.getRawType(); @@ -212,7 +219,8 @@ private static Type scanSuperTypes(TypeVariable typeVar, Type srcType, Class< return null; } - private static ParameterizedType translateParentTypeVars(ParameterizedType srcType, Class srcClass, ParameterizedType parentType) { + private static ParameterizedType translateParentTypeVars(ParameterizedType srcType, Class srcClass, + ParameterizedType parentType) { Type[] parentTypeArgs = parentType.getActualTypeArguments(); Type[] srcTypeArgs = srcType.getActualTypeArguments(); TypeVariable[] srcTypeVars = srcClass.getTypeParameters(); @@ -230,7 +238,7 @@ private static ParameterizedType translateParentTypeVars(ParameterizedType srcTy newParentArgs[i] = parentTypeArgs[i]; } } - return noChange ? parentType : new ParameterizedTypeImpl((Class)parentType.getRawType(), null, newParentArgs); + return noChange ? parentType : new ParameterizedTypeImpl((Class) parentType.getRawType(), null, newParentArgs); } private TypeParameterResolver() { @@ -268,7 +276,8 @@ public Type getRawType() { @Override public String toString() { - return "ParameterizedTypeImpl [rawType=" + rawType + ", ownerType=" + ownerType + ", actualTypeArguments=" + Arrays.toString(actualTypeArguments) + "]"; + return "ParameterizedTypeImpl [rawType=" + rawType + ", ownerType=" + ownerType + ", actualTypeArguments=" + + Arrays.toString(actualTypeArguments) + "]"; } } diff --git a/src/main/java/org/apache/ibatis/reflection/wrapper/BaseWrapper.java b/src/main/java/org/apache/ibatis/reflection/wrapper/BaseWrapper.java index f6ddc8b6036..71c396bdcd1 100644 --- a/src/main/java/org/apache/ibatis/reflection/wrapper/BaseWrapper.java +++ b/src/main/java/org/apache/ibatis/reflection/wrapper/BaseWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -68,7 +68,8 @@ protected Object getCollectionValue(PropertyTokenizer prop, Object collection) { } else if (collection instanceof short[]) { return ((short[]) collection)[i]; } else { - throw new ReflectionException("The '" + prop.getName() + "' property of " + collection + " is not a List or Array."); + throw new ReflectionException( + "The '" + prop.getName() + "' property of " + collection + " is not a List or Array."); } } } @@ -99,7 +100,8 @@ protected void setCollectionValue(PropertyTokenizer prop, Object collection, Obj } else if (collection instanceof short[]) { ((short[]) collection)[i] = (Short) value; } else { - throw new ReflectionException("The '" + prop.getName() + "' property of " + collection + " is not a List or Array."); + throw new ReflectionException( + "The '" + prop.getName() + "' property of " + collection + " is not a List or Array."); } } } diff --git a/src/main/java/org/apache/ibatis/reflection/wrapper/BeanWrapper.java b/src/main/java/org/apache/ibatis/reflection/wrapper/BeanWrapper.java index cae43e0f0e4..6d3f0e3a0b9 100644 --- a/src/main/java/org/apache/ibatis/reflection/wrapper/BeanWrapper.java +++ b/src/main/java/org/apache/ibatis/reflection/wrapper/BeanWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -149,10 +149,12 @@ public MetaObject instantiatePropertyValue(String name, PropertyTokenizer prop, Class type = getSetterType(prop.getName()); try { Object newObject = objectFactory.create(type); - metaValue = MetaObject.forObject(newObject, metaObject.getObjectFactory(), metaObject.getObjectWrapperFactory(), metaObject.getReflectorFactory()); + metaValue = MetaObject.forObject(newObject, metaObject.getObjectFactory(), metaObject.getObjectWrapperFactory(), + metaObject.getReflectorFactory()); set(prop, newObject); } catch (Exception e) { - throw new ReflectionException("Cannot set value of property '" + name + "' because '" + name + "' is null and cannot be instantiated on instance of " + type.getName() + ". Cause:" + e.toString(), e); + throw new ReflectionException("Cannot set value of property '" + name + "' because '" + name + + "' is null and cannot be instantiated on instance of " + type.getName() + ". Cause:" + e.toString(), e); } return metaValue; } @@ -168,21 +170,23 @@ private Object getBeanProperty(PropertyTokenizer prop, Object object) { } catch (RuntimeException e) { throw e; } catch (Throwable t) { - throw new ReflectionException("Could not get property '" + prop.getName() + "' from " + object.getClass() + ". Cause: " + t.toString(), t); + throw new ReflectionException( + "Could not get property '" + prop.getName() + "' from " + object.getClass() + ". Cause: " + t.toString(), t); } } private void setBeanProperty(PropertyTokenizer prop, Object object, Object value) { try { Invoker method = metaClass.getSetInvoker(prop.getName()); - Object[] params = {value}; + Object[] params = { value }; try { method.invoke(object, params); } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); } } catch (Throwable t) { - throw new ReflectionException("Could not set property '" + prop.getName() + "' of '" + object.getClass() + "' with value '" + value + "' Cause: " + t.toString(), t); + throw new ReflectionException("Could not set property '" + prop.getName() + "' of '" + object.getClass() + + "' with value '" + value + "' Cause: " + t.toString(), t); } } diff --git a/src/main/java/org/apache/ibatis/reflection/wrapper/DefaultObjectWrapperFactory.java b/src/main/java/org/apache/ibatis/reflection/wrapper/DefaultObjectWrapperFactory.java index c3285ca0911..331eadae3dd 100644 --- a/src/main/java/org/apache/ibatis/reflection/wrapper/DefaultObjectWrapperFactory.java +++ b/src/main/java/org/apache/ibatis/reflection/wrapper/DefaultObjectWrapperFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -30,7 +30,8 @@ public boolean hasWrapperFor(Object object) { @Override public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) { - throw new ReflectionException("The DefaultObjectWrapperFactory should never be called to provide an ObjectWrapper."); + throw new ReflectionException( + "The DefaultObjectWrapperFactory should never be called to provide an ObjectWrapper."); } } diff --git a/src/main/java/org/apache/ibatis/reflection/wrapper/MapWrapper.java b/src/main/java/org/apache/ibatis/reflection/wrapper/MapWrapper.java index c59b42f6b44..91079f80c6e 100644 --- a/src/main/java/org/apache/ibatis/reflection/wrapper/MapWrapper.java +++ b/src/main/java/org/apache/ibatis/reflection/wrapper/MapWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -137,7 +137,8 @@ public boolean hasGetter(String name) { public MetaObject instantiatePropertyValue(String name, PropertyTokenizer prop, ObjectFactory objectFactory) { HashMap map = new HashMap<>(); set(prop, map); - return MetaObject.forObject(map, metaObject.getObjectFactory(), metaObject.getObjectWrapperFactory(), metaObject.getReflectorFactory()); + return MetaObject.forObject(map, metaObject.getObjectFactory(), metaObject.getObjectWrapperFactory(), + metaObject.getReflectorFactory()); } @Override diff --git a/src/main/java/org/apache/ibatis/scripting/LanguageDriver.java b/src/main/java/org/apache/ibatis/scripting/LanguageDriver.java index ed681587cc8..a008a130484 100644 --- a/src/main/java/org/apache/ibatis/scripting/LanguageDriver.java +++ b/src/main/java/org/apache/ibatis/scripting/LanguageDriver.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -29,32 +29,48 @@ public interface LanguageDriver { * Creates a {@link ParameterHandler} that passes the actual parameters to the the JDBC statement. * * @author Frank D. Martinez [mnesarco] - * @param mappedStatement The mapped statement that is being executed - * @param parameterObject The input parameter object (can be null) - * @param boundSql The resulting SQL once the dynamic language has been executed. + * + * @param mappedStatement + * The mapped statement that is being executed + * @param parameterObject + * The input parameter object (can be null) + * @param boundSql + * The resulting SQL once the dynamic language has been executed. + * * @return the parameter handler + * * @see DefaultParameterHandler */ ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql); /** - * Creates an {@link SqlSource} that will hold the statement read from a mapper xml file. - * It is called during startup, when the mapped statement is read from a class or an xml file. + * Creates an {@link SqlSource} that will hold the statement read from a mapper xml file. It is called during startup, + * when the mapped statement is read from a class or an xml file. + * + * @param configuration + * The MyBatis configuration + * @param script + * XNode parsed from a XML file + * @param parameterType + * input parameter type got from a mapper method or specified in the parameterType xml attribute. Can be + * null. * - * @param configuration The MyBatis configuration - * @param script XNode parsed from a XML file - * @param parameterType input parameter type got from a mapper method or specified in the parameterType xml attribute. Can be null. * @return the sql source */ SqlSource createSqlSource(Configuration configuration, XNode script, Class parameterType); /** - * Creates an {@link SqlSource} that will hold the statement read from an annotation. - * It is called during startup, when the mapped statement is read from a class or an xml file. + * Creates an {@link SqlSource} that will hold the statement read from an annotation. It is called during startup, + * when the mapped statement is read from a class or an xml file. + * + * @param configuration + * The MyBatis configuration + * @param script + * The content of the annotation + * @param parameterType + * input parameter type got from a mapper method or specified in the parameterType xml attribute. Can be + * null. * - * @param configuration The MyBatis configuration - * @param script The content of the annotation - * @param parameterType input parameter type got from a mapper method or specified in the parameterType xml attribute. Can be null. * @return the sql source */ SqlSource createSqlSource(Configuration configuration, String script, Class parameterType); diff --git a/src/main/java/org/apache/ibatis/scripting/defaults/RawLanguageDriver.java b/src/main/java/org/apache/ibatis/scripting/defaults/RawLanguageDriver.java index 731b364517b..bb0a9a16ea7 100644 --- a/src/main/java/org/apache/ibatis/scripting/defaults/RawLanguageDriver.java +++ b/src/main/java/org/apache/ibatis/scripting/defaults/RawLanguageDriver.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -22,11 +22,11 @@ import org.apache.ibatis.session.Configuration; /** - * As of 3.2.4 the default XML language is able to identify static statements - * and create a {@link RawSqlSource}. So there is no need to use RAW unless you - * want to make sure that there is not any dynamic tag for any reason. + * As of 3.2.4 the default XML language is able to identify static statements and create a {@link RawSqlSource}. So + * there is no need to use RAW unless you want to make sure that there is not any dynamic tag for any reason. * * @since 3.2.0 + * * @author Eduardo Macarron */ public class RawLanguageDriver extends XMLLanguageDriver { diff --git a/src/main/java/org/apache/ibatis/scripting/defaults/RawSqlSource.java b/src/main/java/org/apache/ibatis/scripting/defaults/RawSqlSource.java index 556712e5501..f30f6423b2b 100644 --- a/src/main/java/org/apache/ibatis/scripting/defaults/RawSqlSource.java +++ b/src/main/java/org/apache/ibatis/scripting/defaults/RawSqlSource.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -26,10 +26,10 @@ import org.apache.ibatis.session.Configuration; /** - * Static SqlSource. It is faster than {@link DynamicSqlSource} because mappings are - * calculated during startup. + * Static SqlSource. It is faster than {@link DynamicSqlSource} because mappings are calculated during startup. * * @since 3.2.0 + * * @author Eduardo Macarron */ public class RawSqlSource implements SqlSource { diff --git a/src/main/java/org/apache/ibatis/scripting/xmltags/DynamicContext.java b/src/main/java/org/apache/ibatis/scripting/xmltags/DynamicContext.java index 43d84d96729..435d45908a8 100644 --- a/src/main/java/org/apache/ibatis/scripting/xmltags/DynamicContext.java +++ b/src/main/java/org/apache/ibatis/scripting/xmltags/DynamicContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -117,7 +117,7 @@ public Object getProperty(Map context, Object target, Object name) { Object parameterObject = map.get(PARAMETER_OBJECT_KEY); if (parameterObject instanceof Map) { - return ((Map)parameterObject).get(name); + return ((Map) parameterObject).get(name); } return null; diff --git a/src/main/java/org/apache/ibatis/scripting/xmltags/ExpressionEvaluator.java b/src/main/java/org/apache/ibatis/scripting/xmltags/ExpressionEvaluator.java index 09c49a4ba5a..ba2342d98e8 100644 --- a/src/main/java/org/apache/ibatis/scripting/xmltags/ExpressionEvaluator.java +++ b/src/main/java/org/apache/ibatis/scripting/xmltags/ExpressionEvaluator.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -42,7 +42,7 @@ public boolean evaluateBoolean(String expression, Object parameterObject) { /** * @deprecated Since 3.5.9, use the {@link #evaluateIterable(String, Object, boolean)}. */ - @Deprecated + @Deprecated public Iterable evaluateIterable(String expression, Object parameterObject) { return evaluateIterable(expression, parameterObject, false); } @@ -64,7 +64,7 @@ public Iterable evaluateIterable(String expression, Object parameterObject, b } if (value.getClass().isArray()) { // the array may be primitive, so Arrays.asList() may throw - // a ClassCastException (issue 209). Do the work manually + // a ClassCastException (issue 209). Do the work manually // Curse primitives! :) (JGB) int size = Array.getLength(value); List answer = new ArrayList<>(); @@ -77,7 +77,8 @@ public Iterable evaluateIterable(String expression, Object parameterObject, b if (value instanceof Map) { return ((Map) value).entrySet(); } - throw new BuilderException("Error evaluating expression '" + expression + "'. Return value (" + value + ") was not iterable."); + throw new BuilderException( + "Error evaluating expression '" + expression + "'. Return value (" + value + ") was not iterable."); } } diff --git a/src/main/java/org/apache/ibatis/scripting/xmltags/ForEachSqlNode.java b/src/main/java/org/apache/ibatis/scripting/xmltags/ForEachSqlNode.java index 1c7ebbb5f1b..30dfb631c9f 100644 --- a/src/main/java/org/apache/ibatis/scripting/xmltags/ForEachSqlNode.java +++ b/src/main/java/org/apache/ibatis/scripting/xmltags/ForEachSqlNode.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -39,17 +39,20 @@ public class ForEachSqlNode implements SqlNode { private final Configuration configuration; /** - * @deprecated Since 3.5.9, use the {@link #ForEachSqlNode(Configuration, SqlNode, String, Boolean, String, String, String, String, String)}. + * @deprecated Since 3.5.9, use the + * {@link #ForEachSqlNode(Configuration, SqlNode, String, Boolean, String, String, String, String, String)}. */ @Deprecated - public ForEachSqlNode(Configuration configuration, SqlNode contents, String collectionExpression, String index, String item, String open, String close, String separator) { + public ForEachSqlNode(Configuration configuration, SqlNode contents, String collectionExpression, String index, + String item, String open, String close, String separator) { this(configuration, contents, collectionExpression, null, index, item, open, close, separator); } /** * @since 3.5.9 */ - public ForEachSqlNode(Configuration configuration, SqlNode contents, String collectionExpression, Boolean nullable, String index, String item, String open, String close, String separator) { + public ForEachSqlNode(Configuration configuration, SqlNode contents, String collectionExpression, Boolean nullable, + String index, String item, String open, String close, String separator) { this.evaluator = new ExpressionEvaluator(); this.collectionExpression = collectionExpression; this.nullable = nullable; @@ -66,7 +69,7 @@ public ForEachSqlNode(Configuration configuration, SqlNode contents, String coll public boolean apply(DynamicContext context) { Map bindings = context.getBindings(); final Iterable iterable = evaluator.evaluateIterable(collectionExpression, bindings, - Optional.ofNullable(nullable).orElseGet(configuration::isNullableOnForEach)); + Optional.ofNullable(nullable).orElseGet(configuration::isNullableOnForEach)); if (iterable == null || !iterable.iterator().hasNext()) { return true; } @@ -140,7 +143,8 @@ private static class FilteredDynamicContext extends DynamicContext { private final String itemIndex; private final String item; - public FilteredDynamicContext(Configuration configuration,DynamicContext delegate, String itemIndex, String item, int i) { + public FilteredDynamicContext(Configuration configuration, DynamicContext delegate, String itemIndex, String item, + int i) { super(configuration, null); this.delegate = delegate; this.index = i; @@ -183,7 +187,6 @@ public int getUniqueNumber() { } - private class PrefixedContext extends DynamicContext { private final DynamicContext delegate; private final String prefix; diff --git a/src/main/java/org/apache/ibatis/scripting/xmltags/OgnlClassResolver.java b/src/main/java/org/apache/ibatis/scripting/xmltags/OgnlClassResolver.java index 5f6387c9baf..46cde0021e2 100644 --- a/src/main/java/org/apache/ibatis/scripting/xmltags/OgnlClassResolver.java +++ b/src/main/java/org/apache/ibatis/scripting/xmltags/OgnlClassResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -20,9 +20,8 @@ import org.apache.ibatis.io.Resources; /** - * Custom ognl {@code ClassResolver} which behaves same like ognl's - * {@code DefaultClassResolver}. But uses the {@code Resources} - * utility class to find the target class instead of {@code Class#forName(String)}. + * Custom ognl {@code ClassResolver} which behaves same like ognl's {@code DefaultClassResolver}. But uses the + * {@code Resources} utility class to find the target class instead of {@code Class#forName(String)}. * * @author Daniel Guggi * diff --git a/src/main/java/org/apache/ibatis/scripting/xmltags/OgnlMemberAccess.java b/src/main/java/org/apache/ibatis/scripting/xmltags/OgnlMemberAccess.java index 93abdbf082b..da2bfc55ecd 100644 --- a/src/main/java/org/apache/ibatis/scripting/xmltags/OgnlMemberAccess.java +++ b/src/main/java/org/apache/ibatis/scripting/xmltags/OgnlMemberAccess.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -28,6 +28,7 @@ * 'https://github.com/jkuhnert/ognl/blob/OGNL_3_2_1/src/java/ognl/DefaultMemberAccess.java'>DefaultMemberAccess. * * @author Kazuki Shimizu + * * @since 3.5.0 * * @see COMMA = Collections.singletonList(","); - public SetSqlNode(Configuration configuration,SqlNode contents) { + public SetSqlNode(Configuration configuration, SqlNode contents) { super(configuration, contents, "SET", COMMA, null, COMMA); } diff --git a/src/main/java/org/apache/ibatis/scripting/xmltags/TrimSqlNode.java b/src/main/java/org/apache/ibatis/scripting/xmltags/TrimSqlNode.java index 7860214ee15..a86912dd48c 100644 --- a/src/main/java/org/apache/ibatis/scripting/xmltags/TrimSqlNode.java +++ b/src/main/java/org/apache/ibatis/scripting/xmltags/TrimSqlNode.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -36,11 +36,14 @@ public class TrimSqlNode implements SqlNode { private final List suffixesToOverride; private final Configuration configuration; - public TrimSqlNode(Configuration configuration, SqlNode contents, String prefix, String prefixesToOverride, String suffix, String suffixesToOverride) { - this(configuration, contents, prefix, parseOverrides(prefixesToOverride), suffix, parseOverrides(suffixesToOverride)); + public TrimSqlNode(Configuration configuration, SqlNode contents, String prefix, String prefixesToOverride, + String suffix, String suffixesToOverride) { + this(configuration, contents, prefix, parseOverrides(prefixesToOverride), suffix, + parseOverrides(suffixesToOverride)); } - protected TrimSqlNode(Configuration configuration, SqlNode contents, String prefix, List prefixesToOverride, String suffix, List suffixesToOverride) { + protected TrimSqlNode(Configuration configuration, SqlNode contents, String prefix, List prefixesToOverride, + String suffix, List suffixesToOverride) { this.contents = contents; this.prefix = prefix; this.prefixesToOverride = prefixesToOverride; diff --git a/src/main/java/org/apache/ibatis/scripting/xmltags/WhereSqlNode.java b/src/main/java/org/apache/ibatis/scripting/xmltags/WhereSqlNode.java index ab274e3cdd9..b478566df18 100644 --- a/src/main/java/org/apache/ibatis/scripting/xmltags/WhereSqlNode.java +++ b/src/main/java/org/apache/ibatis/scripting/xmltags/WhereSqlNode.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -25,7 +25,8 @@ */ public class WhereSqlNode extends TrimSqlNode { - private static List prefixList = Arrays.asList("AND ","OR ","AND\n", "OR\n", "AND\r", "OR\r", "AND\t", "OR\t"); + private static List prefixList = Arrays.asList("AND ", "OR ", "AND\n", "OR\n", "AND\r", "OR\r", "AND\t", + "OR\t"); public WhereSqlNode(Configuration configuration, SqlNode contents) { super(configuration, contents, "WHERE", prefixList, null, null); diff --git a/src/main/java/org/apache/ibatis/scripting/xmltags/XMLLanguageDriver.java b/src/main/java/org/apache/ibatis/scripting/xmltags/XMLLanguageDriver.java index 8a1521d59a6..ce13a712162 100644 --- a/src/main/java/org/apache/ibatis/scripting/xmltags/XMLLanguageDriver.java +++ b/src/main/java/org/apache/ibatis/scripting/xmltags/XMLLanguageDriver.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -34,7 +34,8 @@ public class XMLLanguageDriver implements LanguageDriver { @Override - public ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) { + public ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, + BoundSql boundSql) { return new DefaultParameterHandler(mappedStatement, parameterObject, boundSql); } diff --git a/src/main/java/org/apache/ibatis/scripting/xmltags/XMLScriptBuilder.java b/src/main/java/org/apache/ibatis/scripting/xmltags/XMLScriptBuilder.java index 09c11732714..3767e446f7d 100644 --- a/src/main/java/org/apache/ibatis/scripting/xmltags/XMLScriptBuilder.java +++ b/src/main/java/org/apache/ibatis/scripting/xmltags/XMLScriptBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -50,7 +50,6 @@ public XMLScriptBuilder(Configuration configuration, XNode context, Class par initNodeHandlerMap(); } - private void initNodeHandlerMap() { nodeHandlerMap.put("trim", new TrimHandler()); nodeHandlerMap.put("where", new WhereHandler()); @@ -177,7 +176,8 @@ public void handleNode(XNode nodeToHandle, List targetContents) { String open = nodeToHandle.getStringAttribute("open"); String close = nodeToHandle.getStringAttribute("close"); String separator = nodeToHandle.getStringAttribute("separator"); - ForEachSqlNode forEachSqlNode = new ForEachSqlNode(configuration, mixedSqlNode, collection, nullable, index, item, open, close, separator); + ForEachSqlNode forEachSqlNode = new ForEachSqlNode(configuration, mixedSqlNode, collection, nullable, index, item, + open, close, separator); targetContents.add(forEachSqlNode); } } @@ -223,7 +223,8 @@ public void handleNode(XNode nodeToHandle, List targetContents) { targetContents.add(chooseSqlNode); } - private void handleWhenOtherwiseNodes(XNode chooseSqlNode, List ifSqlNodes, List defaultSqlNodes) { + private void handleWhenOtherwiseNodes(XNode chooseSqlNode, List ifSqlNodes, + List defaultSqlNodes) { List children = chooseSqlNode.getChildren(); for (XNode child : children) { String nodeName = child.getNode().getNodeName(); diff --git a/src/main/java/org/apache/ibatis/session/AutoMappingUnknownColumnBehavior.java b/src/main/java/org/apache/ibatis/session/AutoMappingUnknownColumnBehavior.java index 08c3657ba91..ba9a6a280db 100644 --- a/src/main/java/org/apache/ibatis/session/AutoMappingUnknownColumnBehavior.java +++ b/src/main/java/org/apache/ibatis/session/AutoMappingUnknownColumnBehavior.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -23,6 +23,7 @@ * Specify the behavior when detects an unknown column (or unknown property type) of automatic mapping target. * * @since 3.4.0 + * * @author Kazuki Shimizu */ public enum AutoMappingUnknownColumnBehavior { @@ -38,8 +39,8 @@ public void doAction(MappedStatement mappedStatement, String columnName, String }, /** - * Output warning log. - * Note: The log level of {@code 'org.apache.ibatis.session.AutoMappingUnknownColumnBehavior'} must be set to {@code WARN}. + * Output warning log. Note: The log level of {@code 'org.apache.ibatis.session.AutoMappingUnknownColumnBehavior'} + * must be set to {@code WARN}. */ WARNING { @Override @@ -49,8 +50,7 @@ public void doAction(MappedStatement mappedStatement, String columnName, String }, /** - * Fail mapping. - * Note: throw {@link SqlSessionException}. + * Fail mapping. Note: throw {@link SqlSessionException}. */ FAILING { @Override @@ -61,26 +61,29 @@ public void doAction(MappedStatement mappedStatement, String columnName, String /** * Perform the action when detects an unknown column (or unknown property type) of automatic mapping target. - * @param mappedStatement current mapped statement - * @param columnName column name for mapping target - * @param propertyName property name for mapping target - * @param propertyType property type for mapping target (If this argument is not null, {@link org.apache.ibatis.type.TypeHandler} for property type is not registered) - */ - public abstract void doAction(MappedStatement mappedStatement, String columnName, String propertyName, Class propertyType); + * + * @param mappedStatement + * current mapped statement + * @param columnName + * column name for mapping target + * @param propertyName + * property name for mapping target + * @param propertyType + * property type for mapping target (If this argument is not null, {@link org.apache.ibatis.type.TypeHandler} + * for property type is not registered) + */ + public abstract void doAction(MappedStatement mappedStatement, String columnName, String propertyName, + Class propertyType); /** * build error message. */ - private static String buildMessage(MappedStatement mappedStatement, String columnName, String property, Class propertyType) { - return new StringBuilder("Unknown column is detected on '") - .append(mappedStatement.getId()) - .append("' auto-mapping. Mapping parameters are ") - .append("[") - .append("columnName=").append(columnName) - .append(",").append("propertyName=").append(property) - .append(",").append("propertyType=").append(propertyType != null ? propertyType.getName() : null) - .append("]") - .toString(); + private static String buildMessage(MappedStatement mappedStatement, String columnName, String property, + Class propertyType) { + return new StringBuilder("Unknown column is detected on '").append(mappedStatement.getId()) + .append("' auto-mapping. Mapping parameters are ").append("[").append("columnName=").append(columnName) + .append(",").append("propertyName=").append(property).append(",").append("propertyType=") + .append(propertyType != null ? propertyType.getName() : null).append("]").toString(); } private static class LogHolder { diff --git a/src/main/java/org/apache/ibatis/session/Configuration.java b/src/main/java/org/apache/ibatis/session/Configuration.java index 82f0f90b263..9dc875f0320 100644 --- a/src/main/java/org/apache/ibatis/session/Configuration.java +++ b/src/main/java/org/apache/ibatis/session/Configuration.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -124,7 +124,8 @@ public class Configuration { protected Class defaultSqlProviderType; protected LocalCacheScope localCacheScope = LocalCacheScope.SESSION; protected JdbcType jdbcTypeForNull = JdbcType.OTHER; - protected Set lazyLoadTriggerMethods = new HashSet<>(Arrays.asList("equals", "clone", "hashCode", "toString")); + protected Set lazyLoadTriggerMethods = new HashSet<>( + Arrays.asList("equals", "clone", "hashCode", "toString")); protected Integer defaultStatementTimeout; protected Integer defaultFetchSize; protected ResultSetType defaultResultSetType; @@ -142,8 +143,7 @@ public class Configuration { protected String databaseId; /** - * Configuration factory class. - * Used to create Configuration for loading deserialized unread properties. + * Configuration factory class. Used to create Configuration for loading deserialized unread properties. * * @see Issue 300 (google code) */ @@ -155,9 +155,10 @@ public class Configuration { protected final TypeAliasRegistry typeAliasRegistry = new TypeAliasRegistry(); protected final LanguageDriverRegistry languageRegistry = new LanguageDriverRegistry(); - protected final Map mappedStatements = new StrictMap("Mapped Statements collection") - .conflictMessageProducer((savedValue, targetValue) -> - ". please check " + savedValue.getResource() + " and " + targetValue.getResource()); + protected final Map mappedStatements = new StrictMap( + "Mapped Statements collection") + .conflictMessageProducer((savedValue, targetValue) -> ". please check " + savedValue.getResource() + " and " + + targetValue.getResource()); protected final Map caches = new StrictMap<>("Caches collection"); protected final Map resultMaps = new StrictMap<>("Result Maps collection"); protected final Map parameterMaps = new StrictMap<>("Parameter Maps collection"); @@ -172,9 +173,8 @@ public class Configuration { protected final Collection incompleteMethods = new LinkedList<>(); /* - * A map holds cache-ref relationship. The key is the namespace that - * references a cache bound to another namespace and the value is the - * namespace which the actual cache is bound to. + * A map holds cache-ref relationship. The key is the namespace that references a cache bound to another namespace and + * the value is the namespace which the actual cache is bound to. */ protected final Map cacheRefMap = new HashMap<>(); @@ -248,9 +248,11 @@ public void setVfsImpl(Class vfsImpl) { } /** - * Gets an applying type when omit a type on sql provider annotation(e.g. {@link org.apache.ibatis.annotations.SelectProvider}). + * Gets an applying type when omit a type on sql provider annotation(e.g. + * {@link org.apache.ibatis.annotations.SelectProvider}). * * @return the default type for sql provider annotation + * * @since 3.5.6 */ public Class getDefaultSqlProviderType() { @@ -258,10 +260,12 @@ public Class getDefaultSqlProviderType() { } /** - * Sets an applying type when omit a type on sql provider annotation(e.g. {@link org.apache.ibatis.annotations.SelectProvider}). + * Sets an applying type when omit a type on sql provider annotation(e.g. + * {@link org.apache.ibatis.annotations.SelectProvider}). * * @param defaultSqlProviderType * the default type for sql provider annotation + * * @since 3.5.6 */ public void setDefaultSqlProviderType(Class defaultSqlProviderType) { @@ -303,7 +307,9 @@ public void setShrinkWhitespacesInSql(boolean shrinkWhitespacesInSql) { /** * Sets the default value of 'nullable' attribute on 'foreach' tag. * - * @param nullableOnForEach If nullable, set to {@code true} + * @param nullableOnForEach + * If nullable, set to {@code true} + * * @since 3.5.9 */ public void setNullableOnForEach(boolean nullableOnForEach) { @@ -312,10 +318,11 @@ public void setNullableOnForEach(boolean nullableOnForEach) { /** * Returns the default value of 'nullable' attribute on 'foreach' tag. - * - *

Default is {@code false}. + *

+ * Default is {@code false}. * * @return If nullable, set to {@code true} + * * @since 3.5.9 */ public boolean isNullableOnForEach() { @@ -398,6 +405,7 @@ public void setAutoMappingBehavior(AutoMappingBehavior autoMappingBehavior) { * Gets the auto mapping unknown column behavior. * * @return the auto mapping unknown column behavior + * * @since 3.4.0 */ public AutoMappingUnknownColumnBehavior getAutoMappingUnknownColumnBehavior() { @@ -409,6 +417,7 @@ public AutoMappingUnknownColumnBehavior getAutoMappingUnknownColumnBehavior() { * * @param autoMappingUnknownColumnBehavior * the new auto mapping unknown column behavior + * * @since 3.4.0 */ public void setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior) { @@ -494,6 +503,7 @@ public void setDefaultStatementTimeout(Integer defaultStatementTimeout) { * Gets the default fetch size. * * @return the default fetch size + * * @since 3.3.0 */ public Integer getDefaultFetchSize() { @@ -505,6 +515,7 @@ public Integer getDefaultFetchSize() { * * @param defaultFetchSize * the new default fetch size + * * @since 3.3.0 */ public void setDefaultFetchSize(Integer defaultFetchSize) { @@ -515,6 +526,7 @@ public void setDefaultFetchSize(Integer defaultFetchSize) { * Gets the default result set type. * * @return the default result set type + * * @since 3.5.2 */ public ResultSetType getDefaultResultSetType() { @@ -526,6 +538,7 @@ public ResultSetType getDefaultResultSetType() { * * @param defaultResultSetType * the new default result set type + * * @since 3.5.2 */ public void setDefaultResultSetType(ResultSetType defaultResultSetType) { @@ -569,9 +582,12 @@ public TypeHandlerRegistry getTypeHandlerRegistry() { } /** - * Set a default {@link TypeHandler} class for {@link Enum}. - * A default {@link TypeHandler} is {@link org.apache.ibatis.type.EnumTypeHandler}. - * @param typeHandler a type handler class for {@link Enum} + * Set a default {@link TypeHandler} class for {@link Enum}. A default {@link TypeHandler} is + * {@link org.apache.ibatis.type.EnumTypeHandler}. + * + * @param typeHandler + * a type handler class for {@link Enum} + * * @since 3.4.5 */ public void setDefaultEnumTypeHandler(Class typeHandler) { @@ -588,6 +604,7 @@ public TypeAliasRegistry getTypeAliasRegistry() { * Gets the mapper registry. * * @return the mapper registry + * * @since 3.2.2 */ public MapperRegistry getMapperRegistry() { @@ -622,6 +639,7 @@ public void setObjectWrapperFactory(ObjectWrapperFactory objectWrapperFactory) { * Gets the interceptors. * * @return the interceptors + * * @since 3.2.2 */ public List getInterceptors() { @@ -648,7 +666,9 @@ public LanguageDriver getDefaultScriptingLanguageInstance() { * * @param langClass * the lang class + * * @return the language driver + * * @since 3.5.1 */ public LanguageDriver getLanguageDriver(Class langClass) { @@ -663,6 +683,7 @@ public LanguageDriver getLanguageDriver(Class langClas * Gets the default scripting language instance. * * @return the default scripting language instance + * * @deprecated Use {@link #getDefaultScriptingLanguageInstance()} */ @Deprecated @@ -674,21 +695,26 @@ public MetaObject newMetaObject(Object object) { return MetaObject.forObject(object, objectFactory, objectWrapperFactory, reflectorFactory); } - public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) { - ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql); + public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, + BoundSql boundSql) { + ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, + parameterObject, boundSql); parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler); return parameterHandler; } - public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler, - ResultHandler resultHandler, BoundSql boundSql) { - ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds); + public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, + ParameterHandler parameterHandler, ResultHandler resultHandler, BoundSql boundSql) { + ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, + resultHandler, boundSql, rowBounds); resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler); return resultSetHandler; } - public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) { - StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql); + public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, + Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) { + StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, + rowBounds, resultHandler, boundSql); statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler); return statementHandler; } @@ -897,9 +923,8 @@ public void addCacheRef(String namespace, String referencedNamespace) { } /* - * Parses all the unprocessed statement nodes in the cache. It is recommended - * to call this method once all the mappers are added as it provides fail-fast - * statement validation. + * Parses all the unprocessed statement nodes in the cache. It is recommended to call this method once all the mappers + * are added as it provides fail-fast statement validation. */ protected void buildAllStatements() { parsePendingResultMaps(); @@ -958,6 +983,7 @@ private void parsePendingResultMaps() { * * @param statementId * the statement id + * * @return namespace or null when id does not contain period. */ protected String extractNamespace(String statementId) { @@ -973,7 +999,8 @@ protected void checkGloballyForDiscriminatedNestedResultMaps(ResultMap rm) { if (value instanceof ResultMap) { ResultMap entryResultMap = (ResultMap) value; if (!entryResultMap.hasNestedResultMaps() && entryResultMap.getDiscriminator() != null) { - Collection discriminatedResultMapNames = entryResultMap.getDiscriminator().getDiscriminatorMap().values(); + Collection discriminatedResultMapNames = entryResultMap.getDiscriminator().getDiscriminatorMap() + .values(); if (discriminatedResultMapNames.contains(rm.getId())) { entryResultMap.forceNestedResultMaps(); } @@ -1029,8 +1056,12 @@ public StrictMap(String name, Map m) { * Assign a function for producing a conflict error message when contains value with the same key. *

* function arguments are 1st is saved value and 2nd is target value. - * @param conflictMessageProducer A function for producing a conflict error message + * + * @param conflictMessageProducer + * A function for producing a conflict error message + * * @return a conflict error message + * * @since 3.5.0 */ public StrictMap conflictMessageProducer(BiFunction conflictMessageProducer) { diff --git a/src/main/java/org/apache/ibatis/session/LocalCacheScope.java b/src/main/java/org/apache/ibatis/session/LocalCacheScope.java index c075f110460..7674d2562a3 100644 --- a/src/main/java/org/apache/ibatis/session/LocalCacheScope.java +++ b/src/main/java/org/apache/ibatis/session/LocalCacheScope.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -19,5 +19,5 @@ * @author Eduardo Macarron */ public enum LocalCacheScope { - SESSION,STATEMENT + SESSION, STATEMENT } diff --git a/src/main/java/org/apache/ibatis/session/SqlSession.java b/src/main/java/org/apache/ibatis/session/SqlSession.java index 5cb759cd95c..bb0f85932dc 100644 --- a/src/main/java/org/apache/ibatis/session/SqlSession.java +++ b/src/main/java/org/apache/ibatis/session/SqlSession.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -24,8 +24,8 @@ import org.apache.ibatis.executor.BatchResult; /** - * The primary Java interface for working with MyBatis. - * Through this interface you can execute commands, get mappers and manage transactions. + * The primary Java interface for working with MyBatis. Through this interface you can execute commands, get mappers and + * manage transactions. * * @author Clinton Begin */ @@ -33,131 +33,190 @@ public interface SqlSession extends Closeable { /** * Retrieve a single row mapped from the statement key. - * @param the returned object type + * + * @param + * the returned object type * @param statement * the statement + * * @return Mapped object */ T selectOne(String statement); /** * Retrieve a single row mapped from the statement key and parameter. - * @param the returned object type - * @param statement Unique identifier matching the statement to use. - * @param parameter A parameter object to pass to the statement. + * + * @param + * the returned object type + * @param statement + * Unique identifier matching the statement to use. + * @param parameter + * A parameter object to pass to the statement. + * * @return Mapped object */ T selectOne(String statement, Object parameter); /** * Retrieve a list of mapped objects from the statement key. - * @param the returned list element type - * @param statement Unique identifier matching the statement to use. + * + * @param + * the returned list element type + * @param statement + * Unique identifier matching the statement to use. + * * @return List of mapped object */ List selectList(String statement); /** * Retrieve a list of mapped objects from the statement key and parameter. - * @param the returned list element type - * @param statement Unique identifier matching the statement to use. - * @param parameter A parameter object to pass to the statement. + * + * @param + * the returned list element type + * @param statement + * Unique identifier matching the statement to use. + * @param parameter + * A parameter object to pass to the statement. + * * @return List of mapped object */ List selectList(String statement, Object parameter); /** - * Retrieve a list of mapped objects from the statement key and parameter, - * within the specified row bounds. - * @param the returned list element type - * @param statement Unique identifier matching the statement to use. - * @param parameter A parameter object to pass to the statement. - * @param rowBounds Bounds to limit object retrieval + * Retrieve a list of mapped objects from the statement key and parameter, within the specified row bounds. + * + * @param + * the returned list element type + * @param statement + * Unique identifier matching the statement to use. + * @param parameter + * A parameter object to pass to the statement. + * @param rowBounds + * Bounds to limit object retrieval + * * @return List of mapped object */ List selectList(String statement, Object parameter, RowBounds rowBounds); /** - * The selectMap is a special case in that it is designed to convert a list - * of results into a Map based on one of the properties in the resulting - * objects. - * Eg. Return a of Map[Integer,Author] for selectMap("selectAuthors","id") - * @param the returned Map keys type - * @param the returned Map values type - * @param statement Unique identifier matching the statement to use. - * @param mapKey The property to use as key for each value in the list. + * The selectMap is a special case in that it is designed to convert a list of results into a Map based on one of the + * properties in the resulting objects. Eg. Return a of Map[Integer,Author] for selectMap("selectAuthors","id") + * + * @param + * the returned Map keys type + * @param + * the returned Map values type + * @param statement + * Unique identifier matching the statement to use. + * @param mapKey + * The property to use as key for each value in the list. + * * @return Map containing key pair data. */ Map selectMap(String statement, String mapKey); /** - * The selectMap is a special case in that it is designed to convert a list - * of results into a Map based on one of the properties in the resulting - * objects. - * @param the returned Map keys type - * @param the returned Map values type - * @param statement Unique identifier matching the statement to use. - * @param parameter A parameter object to pass to the statement. - * @param mapKey The property to use as key for each value in the list. + * The selectMap is a special case in that it is designed to convert a list of results into a Map based on one of the + * properties in the resulting objects. + * + * @param + * the returned Map keys type + * @param + * the returned Map values type + * @param statement + * Unique identifier matching the statement to use. + * @param parameter + * A parameter object to pass to the statement. + * @param mapKey + * The property to use as key for each value in the list. + * * @return Map containing key pair data. */ Map selectMap(String statement, Object parameter, String mapKey); /** - * The selectMap is a special case in that it is designed to convert a list - * of results into a Map based on one of the properties in the resulting - * objects. - * @param the returned Map keys type - * @param the returned Map values type - * @param statement Unique identifier matching the statement to use. - * @param parameter A parameter object to pass to the statement. - * @param mapKey The property to use as key for each value in the list. - * @param rowBounds Bounds to limit object retrieval + * The selectMap is a special case in that it is designed to convert a list of results into a Map based on one of the + * properties in the resulting objects. + * + * @param + * the returned Map keys type + * @param + * the returned Map values type + * @param statement + * Unique identifier matching the statement to use. + * @param parameter + * A parameter object to pass to the statement. + * @param mapKey + * The property to use as key for each value in the list. + * @param rowBounds + * Bounds to limit object retrieval + * * @return Map containing key pair data. */ Map selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds); /** * A Cursor offers the same results as a List, except it fetches data lazily using an Iterator. - * @param the returned cursor element type. - * @param statement Unique identifier matching the statement to use. + * + * @param + * the returned cursor element type. + * @param statement + * Unique identifier matching the statement to use. + * * @return Cursor of mapped objects */ Cursor selectCursor(String statement); /** * A Cursor offers the same results as a List, except it fetches data lazily using an Iterator. - * @param the returned cursor element type. - * @param statement Unique identifier matching the statement to use. - * @param parameter A parameter object to pass to the statement. + * + * @param + * the returned cursor element type. + * @param statement + * Unique identifier matching the statement to use. + * @param parameter + * A parameter object to pass to the statement. + * * @return Cursor of mapped objects */ Cursor selectCursor(String statement, Object parameter); /** * A Cursor offers the same results as a List, except it fetches data lazily using an Iterator. - * @param the returned cursor element type. - * @param statement Unique identifier matching the statement to use. - * @param parameter A parameter object to pass to the statement. - * @param rowBounds Bounds to limit object retrieval + * + * @param + * the returned cursor element type. + * @param statement + * Unique identifier matching the statement to use. + * @param parameter + * A parameter object to pass to the statement. + * @param rowBounds + * Bounds to limit object retrieval + * * @return Cursor of mapped objects */ Cursor selectCursor(String statement, Object parameter, RowBounds rowBounds); /** - * Retrieve a single row mapped from the statement key and parameter - * using a {@code ResultHandler}. - * @param statement Unique identifier matching the statement to use. - * @param parameter A parameter object to pass to the statement. - * @param handler ResultHandler that will handle each retrieved row + * Retrieve a single row mapped from the statement key and parameter using a {@code ResultHandler}. + * + * @param statement + * Unique identifier matching the statement to use. + * @param parameter + * A parameter object to pass to the statement. + * @param handler + * ResultHandler that will handle each retrieved row */ void select(String statement, Object parameter, ResultHandler handler); /** - * Retrieve a single row mapped from the statement - * using a {@code ResultHandler}. - * @param statement Unique identifier matching the statement to use. - * @param handler ResultHandler that will handle each retrieved row + * Retrieve a single row mapped from the statement using a {@code ResultHandler}. + * + * @param statement + * Unique identifier matching the statement to use. + * @param handler + * ResultHandler that will handle each retrieved row */ void select(String statement, ResultHandler handler); @@ -178,81 +237,106 @@ public interface SqlSession extends Closeable { /** * Execute an insert statement. - * @param statement Unique identifier matching the statement to execute. + * + * @param statement + * Unique identifier matching the statement to execute. + * * @return int The number of rows affected by the insert. */ int insert(String statement); /** - * Execute an insert statement with the given parameter object. Any generated - * autoincrement values or selectKey entries will modify the given parameter - * object properties. Only the number of rows affected will be returned. - * @param statement Unique identifier matching the statement to execute. - * @param parameter A parameter object to pass to the statement. + * Execute an insert statement with the given parameter object. Any generated autoincrement values or selectKey + * entries will modify the given parameter object properties. Only the number of rows affected will be returned. + * + * @param statement + * Unique identifier matching the statement to execute. + * @param parameter + * A parameter object to pass to the statement. + * * @return int The number of rows affected by the insert. */ int insert(String statement, Object parameter); /** * Execute an update statement. The number of rows affected will be returned. - * @param statement Unique identifier matching the statement to execute. + * + * @param statement + * Unique identifier matching the statement to execute. + * * @return int The number of rows affected by the update. */ int update(String statement); /** * Execute an update statement. The number of rows affected will be returned. - * @param statement Unique identifier matching the statement to execute. - * @param parameter A parameter object to pass to the statement. + * + * @param statement + * Unique identifier matching the statement to execute. + * @param parameter + * A parameter object to pass to the statement. + * * @return int The number of rows affected by the update. */ int update(String statement, Object parameter); /** * Execute a delete statement. The number of rows affected will be returned. - * @param statement Unique identifier matching the statement to execute. + * + * @param statement + * Unique identifier matching the statement to execute. + * * @return int The number of rows affected by the delete. */ int delete(String statement); /** * Execute a delete statement. The number of rows affected will be returned. - * @param statement Unique identifier matching the statement to execute. - * @param parameter A parameter object to pass to the statement. + * + * @param statement + * Unique identifier matching the statement to execute. + * @param parameter + * A parameter object to pass to the statement. + * * @return int The number of rows affected by the delete. */ int delete(String statement, Object parameter); /** - * Flushes batch statements and commits database connection. - * Note that database connection will not be committed if no updates/deletes/inserts were called. - * To force the commit call {@link SqlSession#commit(boolean)} + * Flushes batch statements and commits database connection. Note that database connection will not be committed if no + * updates/deletes/inserts were called. To force the commit call {@link SqlSession#commit(boolean)} */ void commit(); /** * Flushes batch statements and commits database connection. - * @param force forces connection commit + * + * @param force + * forces connection commit */ void commit(boolean force); /** - * Discards pending batch statements and rolls database connection back. - * Note that database connection will not be rolled back if no updates/deletes/inserts were called. - * To force the rollback call {@link SqlSession#rollback(boolean)} + * Discards pending batch statements and rolls database connection back. Note that database connection will not be + * rolled back if no updates/deletes/inserts were called. To force the rollback call + * {@link SqlSession#rollback(boolean)} */ void rollback(); /** - * Discards pending batch statements and rolls database connection back. - * Note that database connection will not be rolled back if no updates/deletes/inserts were called. - * @param force forces connection rollback + * Discards pending batch statements and rolls database connection back. Note that database connection will not be + * rolled back if no updates/deletes/inserts were called. + * + * @param force + * forces connection rollback */ void rollback(boolean force); /** * Flushes batch statements. + * * @return BatchResult list of updated records + * * @since 3.0.6 */ List flushStatements(); @@ -270,20 +354,26 @@ public interface SqlSession extends Closeable { /** * Retrieves current configuration. + * * @return Configuration */ Configuration getConfiguration(); /** * Retrieves a mapper. - * @param the mapper type - * @param type Mapper interface class + * + * @param + * the mapper type + * @param type + * Mapper interface class + * * @return a mapper bound to this SqlSession */ T getMapper(Class type); /** * Retrieves inner database connection. + * * @return Connection */ Connection getConnection(); diff --git a/src/main/java/org/apache/ibatis/session/SqlSessionFactoryBuilder.java b/src/main/java/org/apache/ibatis/session/SqlSessionFactoryBuilder.java index ea23d799d8d..10b20d68958 100644 --- a/src/main/java/org/apache/ibatis/session/SqlSessionFactoryBuilder.java +++ b/src/main/java/org/apache/ibatis/session/SqlSessionFactoryBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -53,9 +53,9 @@ public SqlSessionFactory build(Reader reader, String environment, Properties pro } finally { ErrorContext.instance().reset(); try { - if (reader != null) { - reader.close(); - } + if (reader != null) { + reader.close(); + } } catch (IOException e) { // Intentionally ignore. Prefer previous error. } @@ -83,9 +83,9 @@ public SqlSessionFactory build(InputStream inputStream, String environment, Prop } finally { ErrorContext.instance().reset(); try { - if (inputStream != null) { - inputStream.close(); - } + if (inputStream != null) { + inputStream.close(); + } } catch (IOException e) { // Intentionally ignore. Prefer previous error. } diff --git a/src/main/java/org/apache/ibatis/session/SqlSessionManager.java b/src/main/java/org/apache/ibatis/session/SqlSessionManager.java index 817d1224003..37eba6b6ea7 100644 --- a/src/main/java/org/apache/ibatis/session/SqlSessionManager.java +++ b/src/main/java/org/apache/ibatis/session/SqlSessionManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -41,10 +41,8 @@ public class SqlSessionManager implements SqlSessionFactory, SqlSession { private SqlSessionManager(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; - this.sqlSessionProxy = (SqlSession) Proxy.newProxyInstance( - SqlSessionFactory.class.getClassLoader(), - new Class[]{SqlSession.class}, - new SqlSessionInterceptor()); + this.sqlSessionProxy = (SqlSession) Proxy.newProxyInstance(SqlSessionFactory.class.getClassLoader(), + new Class[] { SqlSession.class }, new SqlSessionInterceptor()); } public static SqlSessionManager newInstance(Reader reader) { @@ -339,7 +337,7 @@ public void close() { private class SqlSessionInterceptor implements InvocationHandler { public SqlSessionInterceptor() { - // Prevent Synthetic Access + // Prevent Synthetic Access } @Override diff --git a/src/main/java/org/apache/ibatis/session/defaults/DefaultSqlSession.java b/src/main/java/org/apache/ibatis/session/defaults/DefaultSqlSession.java index 2dad6548e3c..2c85905a0d5 100644 --- a/src/main/java/org/apache/ibatis/session/defaults/DefaultSqlSession.java +++ b/src/main/java/org/apache/ibatis/session/defaults/DefaultSqlSession.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -40,8 +40,7 @@ import org.apache.ibatis.session.SqlSession; /** - * The default implementation for {@link SqlSession}. - * Note that this class is not Thread-Safe. + * The default implementation for {@link SqlSession}. Note that this class is not Thread-Safe. * * @author Clinton Begin */ @@ -77,7 +76,8 @@ public T selectOne(String statement, Object parameter) { if (list.size() == 1) { return list.get(0); } else if (list.size() > 1) { - throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size()); + throw new TooManyResultsException( + "Expected one result (or null) to be returned by selectOne(), but found: " + list.size()); } else { return null; } @@ -97,7 +97,7 @@ public Map selectMap(String statement, Object parameter, String map public Map selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) { final List list = selectList(statement, parameter, rowBounds); final DefaultMapResultHandler mapResultHandler = new DefaultMapResultHandler<>(mapKey, - configuration.getObjectFactory(), configuration.getObjectWrapperFactory(), configuration.getReflectorFactory()); + configuration.getObjectFactory(), configuration.getObjectWrapperFactory(), configuration.getReflectorFactory()); final DefaultResultContext context = new DefaultResultContext<>(); for (V o : list) { context.nextResultObject(o); diff --git a/src/main/java/org/apache/ibatis/session/defaults/DefaultSqlSessionFactory.java b/src/main/java/org/apache/ibatis/session/defaults/DefaultSqlSessionFactory.java index 133dde72f3c..f30f308746f 100644 --- a/src/main/java/org/apache/ibatis/session/defaults/DefaultSqlSessionFactory.java +++ b/src/main/java/org/apache/ibatis/session/defaults/DefaultSqlSessionFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -87,7 +87,8 @@ public Configuration getConfiguration() { return configuration; } - private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) { + private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, + boolean autoCommit) { Transaction tx = null; try { final Environment environment = configuration.getEnvironment(); diff --git a/src/test/java/org/apache/ibatis/builder/XmlMapperBuilderTest.java b/src/test/java/org/apache/ibatis/builder/XmlMapperBuilderTest.java index 531174d8489..823dfd3b17f 100644 --- a/src/test/java/org/apache/ibatis/builder/XmlMapperBuilderTest.java +++ b/src/test/java/org/apache/ibatis/builder/XmlMapperBuilderTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -39,7 +39,8 @@ void shouldSuccessfullyLoadXMLMapperFile() throws Exception { Configuration configuration = new Configuration(); String resource = "org/apache/ibatis/builder/AuthorMapper.xml"; try (InputStream inputStream = Resources.getResourceAsStream(resource)) { - XMLMapperBuilder builder = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments()); + XMLMapperBuilder builder = new XMLMapperBuilder(inputStream, configuration, resource, + configuration.getSqlFragments()); builder.parse(); } } @@ -49,7 +50,8 @@ void mappedStatementWithOptions() throws Exception { Configuration configuration = new Configuration(); String resource = "org/apache/ibatis/builder/AuthorMapper.xml"; try (InputStream inputStream = Resources.getResourceAsStream(resource)) { - XMLMapperBuilder builder = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments()); + XMLMapperBuilder builder = new XMLMapperBuilder(inputStream, configuration, resource, + configuration.getSqlFragments()); builder.parse(); MappedStatement mappedStatement = configuration.getMappedStatement("selectWithOptions"); @@ -68,7 +70,8 @@ void mappedStatementWithoutOptionsWhenSpecifyDefaultValue() throws Exception { configuration.setDefaultResultSetType(ResultSetType.SCROLL_INSENSITIVE); String resource = "org/apache/ibatis/builder/AuthorMapper.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); - XMLMapperBuilder builder = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments()); + XMLMapperBuilder builder = new XMLMapperBuilder(inputStream, configuration, resource, + configuration.getSqlFragments()); builder.parse(); inputStream.close(); @@ -78,7 +81,10 @@ void mappedStatementWithoutOptionsWhenSpecifyDefaultValue() throws Exception { @Test void parseExpression() { - BaseBuilder builder = new BaseBuilder(new Configuration()){{}}; + BaseBuilder builder = new BaseBuilder(new Configuration()) { + { + } + }; { Pattern pattern = builder.parseExpression("[0-9]", "[a-z]"); assertThat(pattern.matcher("0").find()).isTrue(); @@ -93,92 +99,104 @@ void parseExpression() { @Test void resolveJdbcTypeWithUndefinedValue() { - BaseBuilder builder = new BaseBuilder(new Configuration()){{}}; + BaseBuilder builder = new BaseBuilder(new Configuration()) { + { + } + }; when(() -> builder.resolveJdbcType("aaa")); - then(caughtException()) - .isInstanceOf(BuilderException.class) - .hasMessageStartingWith("Error resolving JdbcType. Cause: java.lang.IllegalArgumentException: No enum") - .hasMessageEndingWith("org.apache.ibatis.type.JdbcType.aaa"); + then(caughtException()).isInstanceOf(BuilderException.class) + .hasMessageStartingWith("Error resolving JdbcType. Cause: java.lang.IllegalArgumentException: No enum") + .hasMessageEndingWith("org.apache.ibatis.type.JdbcType.aaa"); } @Test void resolveResultSetTypeWithUndefinedValue() { - BaseBuilder builder = new BaseBuilder(new Configuration()){{}}; + BaseBuilder builder = new BaseBuilder(new Configuration()) { + { + } + }; when(() -> builder.resolveResultSetType("bbb")); - then(caughtException()) - .isInstanceOf(BuilderException.class) - .hasMessageStartingWith("Error resolving ResultSetType. Cause: java.lang.IllegalArgumentException: No enum") - .hasMessageEndingWith("org.apache.ibatis.mapping.ResultSetType.bbb"); + then(caughtException()).isInstanceOf(BuilderException.class) + .hasMessageStartingWith("Error resolving ResultSetType. Cause: java.lang.IllegalArgumentException: No enum") + .hasMessageEndingWith("org.apache.ibatis.mapping.ResultSetType.bbb"); } @Test void resolveParameterModeWithUndefinedValue() { - BaseBuilder builder = new BaseBuilder(new Configuration()){{}}; + BaseBuilder builder = new BaseBuilder(new Configuration()) { + { + } + }; when(() -> builder.resolveParameterMode("ccc")); - then(caughtException()) - .isInstanceOf(BuilderException.class) - .hasMessageStartingWith("Error resolving ParameterMode. Cause: java.lang.IllegalArgumentException: No enum") - .hasMessageEndingWith("org.apache.ibatis.mapping.ParameterMode.ccc"); + then(caughtException()).isInstanceOf(BuilderException.class) + .hasMessageStartingWith("Error resolving ParameterMode. Cause: java.lang.IllegalArgumentException: No enum") + .hasMessageEndingWith("org.apache.ibatis.mapping.ParameterMode.ccc"); } @Test void createInstanceWithAbstractClass() { - BaseBuilder builder = new BaseBuilder(new Configuration()){{}}; + BaseBuilder builder = new BaseBuilder(new Configuration()) { + { + } + }; when(() -> builder.createInstance("org.apache.ibatis.builder.BaseBuilder")); - then(caughtException()) - .isInstanceOf(BuilderException.class) - .hasMessage("Error creating instance. Cause: java.lang.NoSuchMethodException: org.apache.ibatis.builder.BaseBuilder.()"); + then(caughtException()).isInstanceOf(BuilderException.class).hasMessage( + "Error creating instance. Cause: java.lang.NoSuchMethodException: org.apache.ibatis.builder.BaseBuilder.()"); } @Test void resolveClassWithNotFound() { - BaseBuilder builder = new BaseBuilder(new Configuration()){{}}; + BaseBuilder builder = new BaseBuilder(new Configuration()) { + { + } + }; when(() -> builder.resolveClass("ddd")); - then(caughtException()) - .isInstanceOf(BuilderException.class) - .hasMessage("Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'ddd'. Cause: java.lang.ClassNotFoundException: Cannot find class: ddd"); + then(caughtException()).isInstanceOf(BuilderException.class).hasMessage( + "Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'ddd'. Cause: java.lang.ClassNotFoundException: Cannot find class: ddd"); } @Test void resolveTypeHandlerTypeHandlerAliasIsNull() { - BaseBuilder builder = new BaseBuilder(new Configuration()){{}}; - TypeHandler typeHandler = builder.resolveTypeHandler(String.class, (String)null); + BaseBuilder builder = new BaseBuilder(new Configuration()) { + { + } + }; + TypeHandler typeHandler = builder.resolveTypeHandler(String.class, (String) null); assertThat(typeHandler).isNull(); } @Test void resolveTypeHandlerNoAssignable() { - BaseBuilder builder = new BaseBuilder(new Configuration()){{}}; + BaseBuilder builder = new BaseBuilder(new Configuration()) { + { + } + }; when(() -> builder.resolveTypeHandler(String.class, "integer")); - then(caughtException()) - .isInstanceOf(BuilderException.class) - .hasMessage("Type java.lang.Integer is not a valid TypeHandler because it does not implement TypeHandler interface"); + then(caughtException()).isInstanceOf(BuilderException.class).hasMessage( + "Type java.lang.Integer is not a valid TypeHandler because it does not implement TypeHandler interface"); } @Test void setCurrentNamespaceValueIsNull() { MapperBuilderAssistant builder = new MapperBuilderAssistant(new Configuration(), "resource"); when(() -> builder.setCurrentNamespace(null)); - then(caughtException()) - .isInstanceOf(BuilderException.class) - .hasMessage("The mapper element requires a namespace attribute to be specified."); + then(caughtException()).isInstanceOf(BuilderException.class) + .hasMessage("The mapper element requires a namespace attribute to be specified."); } @Test void useCacheRefNamespaceIsNull() { MapperBuilderAssistant builder = new MapperBuilderAssistant(new Configuration(), "resource"); when(() -> builder.useCacheRef(null)); - then(caughtException()) - .isInstanceOf(BuilderException.class) - .hasMessage("cache-ref element requires a namespace attribute."); + then(caughtException()).isInstanceOf(BuilderException.class) + .hasMessage("cache-ref element requires a namespace attribute."); } @Test void useCacheRefNamespaceIsUndefined() { MapperBuilderAssistant builder = new MapperBuilderAssistant(new Configuration(), "resource"); when(() -> builder.useCacheRef("eee")); - then(caughtException()) - .hasMessage("No cache for namespace 'eee' could be found."); + then(caughtException()).hasMessage("No cache for namespace 'eee' could be found."); } @Test @@ -186,39 +204,44 @@ void shouldFailedLoadXMLMapperFile() throws Exception { Configuration configuration = new Configuration(); String resource = "org/apache/ibatis/builder/ProblemMapper.xml"; try (InputStream inputStream = Resources.getResourceAsStream(resource)) { - XMLMapperBuilder builder = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments()); + XMLMapperBuilder builder = new XMLMapperBuilder(inputStream, configuration, resource, + configuration.getSqlFragments()); Exception exception = Assertions.assertThrows(BuilderException.class, builder::parse); - Assertions.assertTrue(exception.getMessage().contains("Error parsing Mapper XML. The XML location is 'org/apache/ibatis/builder/ProblemMapper.xml'")); + Assertions.assertTrue(exception.getMessage() + .contains("Error parsing Mapper XML. The XML location is 'org/apache/ibatis/builder/ProblemMapper.xml'")); } } -// @Test -// public void shouldNotLoadTheSameNamespaceFromTwoResourcesWithDifferentNames() throws Exception { -// Configuration configuration = new Configuration(); -// String resource = "org/apache/ibatis/builder/AuthorMapper.xml"; -// InputStream inputStream = Resources.getResourceAsStream(resource); -// XMLMapperBuilder builder = new XMLMapperBuilder(inputStream, configuration, "name1", configuration.getSqlFragments()); -// builder.parse(); -// InputStream inputStream2 = Resources.getResourceAsStream(resource); -// XMLMapperBuilder builder2 = new XMLMapperBuilder(inputStream2, configuration, "name2", configuration.getSqlFragments()); -// builder2.parse(); -// } - - @Test - void errorResultMapLocation() throws Exception { - Configuration configuration = new Configuration(); - String resource = "org/apache/ibatis/builder/ProblemResultMapper.xml"; - try (InputStream inputStream = Resources.getResourceAsStream(resource)) { - XMLMapperBuilder builder = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments()); - builder.parse(); - String resultMapName = "java.lang.String"; - // namespace + "." + id - String statementId = "org.mybatis.spring.ErrorProblemMapper" + "." + "findProblemResultMapTest"; - // same as MapperBuilderAssistant.getStatementResultMaps Exception message - String message = "Could not find result map '" + resultMapName + "' referenced from '" + statementId + "'"; - IncompleteElementException exception = Assertions.assertThrows(IncompleteElementException.class, - ()-> configuration.getMappedStatement("findProblemTypeTest")); - assertThat(exception.getMessage()).isEqualTo(message); - } - } + // @Test + // public void shouldNotLoadTheSameNamespaceFromTwoResourcesWithDifferentNames() throws Exception { + // Configuration configuration = new Configuration(); + // String resource = "org/apache/ibatis/builder/AuthorMapper.xml"; + // InputStream inputStream = Resources.getResourceAsStream(resource); + // XMLMapperBuilder builder = new XMLMapperBuilder(inputStream, configuration, "name1", + // configuration.getSqlFragments()); + // builder.parse(); + // InputStream inputStream2 = Resources.getResourceAsStream(resource); + // XMLMapperBuilder builder2 = new XMLMapperBuilder(inputStream2, configuration, "name2", + // configuration.getSqlFragments()); + // builder2.parse(); + // } + + @Test + void errorResultMapLocation() throws Exception { + Configuration configuration = new Configuration(); + String resource = "org/apache/ibatis/builder/ProblemResultMapper.xml"; + try (InputStream inputStream = Resources.getResourceAsStream(resource)) { + XMLMapperBuilder builder = new XMLMapperBuilder(inputStream, configuration, resource, + configuration.getSqlFragments()); + builder.parse(); + String resultMapName = "java.lang.String"; + // namespace + "." + id + String statementId = "org.mybatis.spring.ErrorProblemMapper" + "." + "findProblemResultMapTest"; + // same as MapperBuilderAssistant.getStatementResultMaps Exception message + String message = "Could not find result map '" + resultMapName + "' referenced from '" + statementId + "'"; + IncompleteElementException exception = Assertions.assertThrows(IncompleteElementException.class, + () -> configuration.getMappedStatement("findProblemTypeTest")); + assertThat(exception.getMessage()).isEqualTo(message); + } + } } diff --git a/src/test/java/org/apache/ibatis/cursor/defaults/DefaultCursorTest.java b/src/test/java/org/apache/ibatis/cursor/defaults/DefaultCursorTest.java index c2d94a6fbdd..fadcb3dd05d 100644 --- a/src/test/java/org/apache/ibatis/cursor/defaults/DefaultCursorTest.java +++ b/src/test/java/org/apache/ibatis/cursor/defaults/DefaultCursorTest.java @@ -104,30 +104,24 @@ private MappedStatement getNestedAndOrderedMappedStatement() { final Configuration config = new Configuration(); final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - ResultMap nestedResultMap = new ResultMap.Builder(config, "roleMap", HashMap.class, - new ArrayList() { - { - add(new ResultMapping.Builder(config, "role", "role", registry.getTypeHandler(String.class)) - .build()); - } - }).build(); + ResultMap nestedResultMap = new ResultMap.Builder(config, "roleMap", HashMap.class, new ArrayList() { + { + add(new ResultMapping.Builder(config, "role", "role", registry.getTypeHandler(String.class)).build()); + } + }).build(); config.addResultMap(nestedResultMap); return new MappedStatement.Builder(config, "selectPerson", new StaticSqlSource(config, "select person..."), - SqlCommandType.SELECT).resultMaps( - new ArrayList() { + SqlCommandType.SELECT).resultMaps(new ArrayList() { { add(new ResultMap.Builder(config, "personMap", HashMap.class, new ArrayList() { { - add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(Integer.class)) - .build()); + add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(Integer.class)).build()); add(new ResultMapping.Builder(config, "roles").nestedResultMapId("roleMap").build()); } }).build()); } - }) - .resultOrdered(true) - .build(); + }).resultOrdered(true).build(); } /* diff --git a/src/test/java/org/apache/ibatis/exceptions/GeneralExceptionsTest.java b/src/test/java/org/apache/ibatis/exceptions/GeneralExceptionsTest.java index 5cd1d062722..8965798054c 100644 --- a/src/test/java/org/apache/ibatis/exceptions/GeneralExceptionsTest.java +++ b/src/test/java/org/apache/ibatis/exceptions/GeneralExceptionsTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -49,34 +49,24 @@ void should() { @Test void shouldInstantiateAndThrowAllCustomExceptions() throws Exception { - Class[] exceptionTypes = { - BindingException.class, - CacheException.class, - DataSourceException.class, - ExecutorException.class, - LogException.class, - ParsingException.class, - BuilderException.class, - PluginException.class, - ReflectionException.class, - PersistenceException.class, - SqlSessionException.class, - TransactionException.class, - TypeException.class, - ScriptingException.class - }; + Class[] exceptionTypes = { BindingException.class, CacheException.class, DataSourceException.class, + ExecutorException.class, LogException.class, ParsingException.class, BuilderException.class, + PluginException.class, ReflectionException.class, PersistenceException.class, SqlSessionException.class, + TransactionException.class, TypeException.class, ScriptingException.class }; for (Class exceptionType : exceptionTypes) { testExceptionConstructors(exceptionType); } } - private void testExceptionConstructors(Class exceptionType) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { + private void testExceptionConstructors(Class exceptionType) + throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { Exception e = (Exception) exceptionType.getDeclaredConstructor().newInstance(); testThrowException(e); e = (Exception) exceptionType.getConstructor(String.class).newInstance(EXPECTED_MESSAGE); testThrowException(e); - e = (Exception) exceptionType.getConstructor(String.class, Throwable.class).newInstance(EXPECTED_MESSAGE, EXPECTED_CAUSE); + e = (Exception) exceptionType.getConstructor(String.class, Throwable.class).newInstance(EXPECTED_MESSAGE, + EXPECTED_CAUSE); testThrowException(e); e = (Exception) exceptionType.getConstructor(Throwable.class).newInstance(EXPECTED_CAUSE); testThrowException(e); diff --git a/src/test/java/org/apache/ibatis/executor/ExecutorTestHelper.java b/src/test/java/org/apache/ibatis/executor/ExecutorTestHelper.java index 193c0395ba4..0b5922e3c74 100644 --- a/src/test/java/org/apache/ibatis/executor/ExecutorTestHelper.java +++ b/src/test/java/org/apache/ibatis/executor/ExecutorTestHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -58,315 +58,333 @@ class ExecutorTestHelper { static final Cache authorCache; static { - authorCache = - new SynchronizedCache( - new SerializedCache( - new LoggingCache( - new ScheduledCache( - new PerpetualCache("author_cache"))))); + authorCache = new SynchronizedCache( + new SerializedCache(new LoggingCache(new ScheduledCache(new PerpetualCache("author_cache"))))); } static MappedStatement prepareInsertAuthorMappedStatement(final Configuration config) { final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - return new MappedStatement.Builder(config, "insertAuthor", new StaticSqlSource(config,"INSERT INTO author (id,username,password,email,bio,favourite_section) values(?,?,?,?,?,?)"), SqlCommandType.INSERT) - .parameterMap( - new ParameterMap.Builder( - config, "defaultParameterMap", Author.class, - new ArrayList() { - { - add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build()); - add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)).build()); - add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)).build()); - add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)).build()); - add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).build()); - add(new ParameterMapping.Builder(config, "favouriteSection", registry.getTypeHandler(Section.class)).jdbcType(JdbcType.VARCHAR).build()); - } - }).build()) - .cache(authorCache).build(); + return new MappedStatement.Builder(config, "insertAuthor", + new StaticSqlSource(config, + "INSERT INTO author (id,username,password,email,bio,favourite_section) values(?,?,?,?,?,?)"), + SqlCommandType.INSERT).parameterMap( + new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList() { + { + add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build()); + add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)).build()); + add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)).build()); + add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)).build()); + add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)) + .jdbcType(JdbcType.VARCHAR).build()); + add(new ParameterMapping.Builder(config, "favouriteSection", registry.getTypeHandler(Section.class)) + .jdbcType(JdbcType.VARCHAR).build()); + } + }).build()).cache(authorCache).build(); } static MappedStatement prepareInsertAuthorMappedStatementWithAutoKey(final Configuration config) { final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - return new MappedStatement.Builder(config, "insertAuthor", new StaticSqlSource(config,"INSERT INTO author (username,password,email,bio,favourite_section) values(?,?,?,?,?)"), SqlCommandType.INSERT) - .parameterMap( + return new MappedStatement.Builder(config, "insertAuthor", + new StaticSqlSource(config, + "INSERT INTO author (username,password,email,bio,favourite_section) values(?,?,?,?,?)"), + SqlCommandType.INSERT).parameterMap( new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList() { { add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)).build()); add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)).build()); add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)).build()); - add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).build()); - add(new ParameterMapping.Builder(config, "favouriteSection", registry.getTypeHandler(Section.class)).jdbcType(JdbcType.VARCHAR).build()); + add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)) + .jdbcType(JdbcType.VARCHAR).build()); + add(new ParameterMapping.Builder(config, "favouriteSection", registry.getTypeHandler(Section.class)) + .jdbcType(JdbcType.VARCHAR).build()); } - }).build()) - .cache(authorCache) - .keyGenerator(Jdbc3KeyGenerator.INSTANCE) - .keyProperty("id") - .build(); + }).build()).cache(authorCache).keyGenerator(Jdbc3KeyGenerator.INSTANCE).keyProperty("id").build(); } static MappedStatement prepareInsertAuthorProc(final Configuration config) { final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - return new MappedStatement.Builder(config, "insertAuthorProc", new StaticSqlSource(config,"{call insertAuthor(?,?,?,?)}"), SqlCommandType.INSERT) - .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class, - new ArrayList() { + return new MappedStatement.Builder(config, "insertAuthorProc", + new StaticSqlSource(config, "{call insertAuthor(?,?,?,?)}"), SqlCommandType.INSERT).parameterMap( + new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList() { { add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build()); add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)).build()); add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)).build()); add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)).build()); } - }).build()) - .cache(authorCache).build(); + }).build()).cache(authorCache).build(); } static MappedStatement prepareUpdateAuthorMappedStatement(final Configuration config) { final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - return new MappedStatement.Builder(config, "updateAuthor", new StaticSqlSource(config,"UPDATE author SET username = ?, password = ?, email = ?, bio = ? WHERE id = ?"), SqlCommandType.UPDATE) - .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class, - new ArrayList() { + return new MappedStatement.Builder(config, "updateAuthor", + new StaticSqlSource(config, "UPDATE author SET username = ?, password = ?, email = ?, bio = ? WHERE id = ?"), + SqlCommandType.UPDATE).parameterMap( + new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList() { { add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)).build()); add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)).build()); add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)).build()); - add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).build()); + add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)) + .jdbcType(JdbcType.VARCHAR).build()); add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build()); } - }).build()) - .cache(authorCache).build(); + }).build()).cache(authorCache).build(); } static MappedStatement prepareDeleteAuthorMappedStatement(final Configuration config) { final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - return new MappedStatement.Builder(config, "deleteAuthor", new StaticSqlSource(config,"DELETE FROM author WHERE id = ?"), SqlCommandType.DELETE) - .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class, - new ArrayList() { + return new MappedStatement.Builder(config, "deleteAuthor", + new StaticSqlSource(config, "DELETE FROM author WHERE id = ?"), SqlCommandType.DELETE).parameterMap( + new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList() { { add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build()); } - }).build()) - .cache(authorCache) - .build(); + }).build()).cache(authorCache).build(); } static MappedStatement prepareSelectOneAuthorMappedStatement(final Configuration config) { final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - final ResultMap rm = new ResultMap.Builder(config, "defaultResultMap", Author.class, new - ArrayList() { + final ResultMap rm = new ResultMap.Builder(config, "defaultResultMap", Author.class, + new ArrayList() { { add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class)).build()); - add(new ResultMapping.Builder(config, "username", "username", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "password", "password", registry.getTypeHandler(String.class)).build()); + add(new ResultMapping.Builder(config, "username", "username", registry.getTypeHandler(String.class)) + .build()); + add(new ResultMapping.Builder(config, "password", "password", registry.getTypeHandler(String.class)) + .build()); add(new ResultMapping.Builder(config, "email", "email", registry.getTypeHandler(String.class)).build()); add(new ResultMapping.Builder(config, "bio", "bio", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "favouriteSection", "favourite_section", registry.getTypeHandler(Section.class)).build()); + add(new ResultMapping.Builder(config, "favouriteSection", "favourite_section", + registry.getTypeHandler(Section.class)).build()); } }).build(); - return new MappedStatement.Builder(config, "selectAuthor", new StaticSqlSource(config,"SELECT * FROM author WHERE id = ?"), SqlCommandType.SELECT) - .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class, - new ArrayList() { + return new MappedStatement.Builder(config, "selectAuthor", + new StaticSqlSource(config, "SELECT * FROM author WHERE id = ?"), SqlCommandType.SELECT).parameterMap( + new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList() { { add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build()); } - }).build()) - .resultMaps(new ArrayList() { - { - add(rm); - } - }) - .cache(authorCache).build(); + }).build()).resultMaps(new ArrayList() { + { + add(rm); + } + }).cache(authorCache).build(); } static MappedStatement prepareSelectAllAuthorsAutoMappedStatement(final Configuration config) { final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - return new MappedStatement.Builder(config, "selectAuthorAutoMap", new StaticSqlSource(config,"SELECT * FROM author ORDER BY id"), SqlCommandType.SELECT) - .resultMaps(new ArrayList() { - { - add(new ResultMap.Builder(config, "defaultResultMap", Author.class, new ArrayList() { + return new MappedStatement.Builder(config, "selectAuthorAutoMap", + new StaticSqlSource(config, "SELECT * FROM author ORDER BY id"), SqlCommandType.SELECT) + .resultMaps(new ArrayList() { { - add(new ResultMapping.Builder(config, "favouriteSection", "favourite_section", registry.getTypeHandler(Section.class)).build()); - add(new ResultMapping.Builder(config, null, "not_exists", Object.class).build()); + add(new ResultMap.Builder(config, "defaultResultMap", Author.class, new ArrayList() { + { + add(new ResultMapping.Builder(config, "favouriteSection", "favourite_section", + registry.getTypeHandler(Section.class)).build()); + add(new ResultMapping.Builder(config, null, "not_exists", Object.class).build()); + } + }).build()); } - }).build()); - } - }).fetchSize(1000).timeout(2000).build(); + }).fetchSize(1000).timeout(2000).build(); } static MappedStatement prepareSelectOneAuthorMappedStatementWithConstructorResults(final Configuration config) { final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - return new MappedStatement.Builder(config, "selectAuthor", new StaticSqlSource(config,"SELECT * FROM author WHERE id = ?"), SqlCommandType.SELECT) - .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class, - new ArrayList() { + return new MappedStatement.Builder(config, "selectAuthor", + new StaticSqlSource(config, "SELECT * FROM author WHERE id = ?"), SqlCommandType.SELECT).parameterMap( + new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList() { { add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build()); } - }).build()) - .resultMaps(new ArrayList() { - { - add(new ResultMap.Builder(config, "defaultResultMap", Author.class, new ArrayList() { + }).build()).resultMaps(new ArrayList() { { - add(new ResultMapping.Builder(config, null, "id", registry.getTypeHandler(Integer.class)).javaType(int.class).flags(new ArrayList() { + add(new ResultMap.Builder(config, "defaultResultMap", Author.class, new ArrayList() { { - add(ResultFlag.CONSTRUCTOR); + add(new ResultMapping.Builder(config, null, "id", registry.getTypeHandler(Integer.class)) + .javaType(int.class).flags(new ArrayList() { + { + add(ResultFlag.CONSTRUCTOR); + } + }).build()); + add(new ResultMapping.Builder(config, "username", "username", registry.getTypeHandler(String.class)) + .build()); + add(new ResultMapping.Builder(config, "password", "password", registry.getTypeHandler(String.class)) + .build()); + add(new ResultMapping.Builder(config, "email", "email", registry.getTypeHandler(String.class)) + .build()); + add(new ResultMapping.Builder(config, "bio", "bio", registry.getTypeHandler(String.class)).build()); + add(new ResultMapping.Builder(config, "favouriteSection", "favourite_section", + registry.getTypeHandler(Section.class)).build()); } }).build()); - add(new ResultMapping.Builder(config, "username", "username", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "password", "password", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "email", "email", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "bio", "bio", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "favouriteSection", "favourite_section", registry.getTypeHandler(Section.class)).build()); } - }).build()); - } - }) - .cache(authorCache) - .build(); + }).cache(authorCache).build(); } static MappedStatement prepareSelectTwoSetsOfAuthorsProc(final Configuration config) { final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - return new MappedStatement.Builder(config, "selectTwoSetsOfAuthors", new StaticSqlSource(config,"{call selectTwoSetsOfAuthors(?,?)}"), SqlCommandType.SELECT) - .statementType(StatementType.CALLABLE) - .parameterMap(new ParameterMap.Builder( - config, "defaultParameterMap", Author.class, - new ArrayList() { - { - add(new ParameterMapping.Builder(config, "id1", registry.getTypeHandler(int.class)).build()); - add(new ParameterMapping.Builder(config, "id2", registry.getTypeHandler(int.class)).build()); - } - }).build()) - .resultMaps(new ArrayList() { - { - ResultMap map = new ResultMap.Builder(config, "defaultResultMap", Author.class, new ArrayList() { + return new MappedStatement.Builder(config, "selectTwoSetsOfAuthors", + new StaticSqlSource(config, "{call selectTwoSetsOfAuthors(?,?)}"), SqlCommandType.SELECT) + .statementType(StatementType.CALLABLE).parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", + Author.class, new ArrayList() { + { + add(new ParameterMapping.Builder(config, "id1", registry.getTypeHandler(int.class)).build()); + add(new ParameterMapping.Builder(config, "id2", registry.getTypeHandler(int.class)).build()); + } + }).build()) + .resultMaps(new ArrayList() { { - add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class)).build()); - add(new ResultMapping.Builder(config, "username", "username", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "password", "password", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "email", "email", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "bio", "bio", registry.getTypeHandler(String.class)).build()); + ResultMap map = new ResultMap.Builder(config, "defaultResultMap", Author.class, + new ArrayList() { + { + add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class)).build()); + add(new ResultMapping.Builder(config, "username", "username", + registry.getTypeHandler(String.class)).build()); + add(new ResultMapping.Builder(config, "password", "password", + registry.getTypeHandler(String.class)).build()); + add(new ResultMapping.Builder(config, "email", "email", registry.getTypeHandler(String.class)) + .build()); + add(new ResultMapping.Builder(config, "bio", "bio", registry.getTypeHandler(String.class)) + .build()); + } + }).build(); + add(map); + add(map); } }).build(); - add(map); - add(map); - } - }).build(); } static MappedStatement prepareSelectAuthorViaOutParams(final Configuration config) { final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - return new MappedStatement.Builder(config, "selectAuthorViaOutParams", new StaticSqlSource(config, "{call selectAuthorViaOutParams(?,?,?,?,?)}"), SqlCommandType.SELECT) - .statementType(StatementType.CALLABLE) - .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class, - new ArrayList() { - { - add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build()); - add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build()); - add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build()); - add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build()); - add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build()); - } - }).build()) - .resultMaps(new ArrayList<>()) - .cache(authorCache).build(); + return new MappedStatement.Builder(config, "selectAuthorViaOutParams", + new StaticSqlSource(config, "{call selectAuthorViaOutParams(?,?,?,?,?)}"), SqlCommandType.SELECT) + .statementType(StatementType.CALLABLE).parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", + Author.class, new ArrayList() { + { + add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build()); + add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)) + .jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build()); + add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)) + .jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build()); + add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)) + .jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build()); + add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)) + .jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build()); + } + }).build()) + .resultMaps(new ArrayList<>()).cache(authorCache).build(); } static MappedStatement prepareSelectDiscriminatedPost(final Configuration config) { final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - final ResultMap discriminatorResultMap = new ResultMap.Builder(config, "postResultMap", HashMap.class, new ArrayList() { - { - add(new ResultMapping.Builder(config, "subject", "subject", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "body", "body", registry.getTypeHandler(String.class)).build()); - } - }).build(); + final ResultMap discriminatorResultMap = new ResultMap.Builder(config, "postResultMap", HashMap.class, + new ArrayList() { + { + add(new ResultMapping.Builder(config, "subject", "subject", registry.getTypeHandler(String.class)).build()); + add(new ResultMapping.Builder(config, "body", "body", registry.getTypeHandler(String.class)).build()); + } + }).build(); config.addResultMap(discriminatorResultMap); - return new MappedStatement.Builder(config, "selectPosts", new StaticSqlSource(config,"SELECT * FROM post"), SqlCommandType.SELECT) - .resultMaps(new ArrayList() { + return new MappedStatement.Builder(config, "selectPosts", new StaticSqlSource(config, "SELECT * FROM post"), + SqlCommandType.SELECT).resultMaps(new ArrayList() { { add(new ResultMap.Builder(config, "defaultResultMap", HashMap.class, new ArrayList() { { add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class)).build()); - add(new ResultMapping.Builder(config, "blog_id", "blog_id", registry.getTypeHandler(int.class)).build()); + add(new ResultMapping.Builder(config, "blog_id", "blog_id", registry.getTypeHandler(int.class)) + .build()); } - }) - .discriminator(new Discriminator.Builder( - config, new ResultMapping.Builder(config, "section", "section", registry.getTypeHandler(String.class)).build(), - new HashMap() { - { - put("NEWS", discriminatorResultMap.getId()); - put("VIDEOS", discriminatorResultMap.getId()); - put("PODCASTS", discriminatorResultMap.getId()); - //NEWS left out on purpose. - } - }).build()).build()); + }).discriminator(new Discriminator.Builder(config, + new ResultMapping.Builder(config, "section", "section", registry.getTypeHandler(String.class)).build(), + new HashMap() { + { + put("NEWS", discriminatorResultMap.getId()); + put("VIDEOS", discriminatorResultMap.getId()); + put("PODCASTS", discriminatorResultMap.getId()); + // NEWS left out on purpose. + } + }).build()).build()); } }).build(); } static MappedStatement createInsertAuthorWithIDof99MappedStatement(final Configuration config) { - return new MappedStatement.Builder(config, "insertAuthor", new StaticSqlSource(config,"INSERT INTO author (id,username,password,email,bio) values(99,'someone','******','someone@apache.org',null)"), SqlCommandType.INSERT) - .statementType(StatementType.STATEMENT) - .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class, - new ArrayList<>()).build()) - .cache(authorCache) - .build(); + return new MappedStatement.Builder(config, "insertAuthor", new StaticSqlSource(config, + "INSERT INTO author (id,username,password,email,bio) values(99,'someone','******','someone@apache.org',null)"), + SqlCommandType.INSERT) + .statementType(StatementType.STATEMENT) + .parameterMap( + new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList<>()).build()) + .cache(authorCache).build(); } static MappedStatement createSelectAuthorWithIDof99MappedStatement(final Configuration config) { final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - return new MappedStatement.Builder(config, "selectAuthor", new StaticSqlSource(config,"SELECT * FROM author WHERE id = 99"), SqlCommandType.SELECT) - .statementType(StatementType.STATEMENT) - .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList<>()).build()) - .resultMaps(new ArrayList() { - { - add(new ResultMap.Builder(config, "defaultResultMap", Author.class, new ArrayList() { + return new MappedStatement.Builder(config, "selectAuthor", + new StaticSqlSource(config, "SELECT * FROM author WHERE id = 99"), SqlCommandType.SELECT) + .statementType(StatementType.STATEMENT) + .parameterMap( + new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList<>()).build()) + .resultMaps(new ArrayList() { { - add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class)).build()); - add(new ResultMapping.Builder(config, "username", "username", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "password", "password", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "email", "email", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "bio", "bio", registry.getTypeHandler(String.class)).build()); + add(new ResultMap.Builder(config, "defaultResultMap", Author.class, new ArrayList() { + { + add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class)).build()); + add(new ResultMapping.Builder(config, "username", "username", registry.getTypeHandler(String.class)) + .build()); + add(new ResultMapping.Builder(config, "password", "password", registry.getTypeHandler(String.class)) + .build()); + add(new ResultMapping.Builder(config, "email", "email", registry.getTypeHandler(String.class)) + .build()); + add(new ResultMapping.Builder(config, "bio", "bio", registry.getTypeHandler(String.class)).build()); + } + }).build()); } - }).build()); - } - }).build(); + }).build(); } static MappedStatement prepareComplexSelectBlogMappedStatement(final Configuration config) { final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - final SqlSource sqlSource = new StaticSqlSource(config, "SELECT b.id, b.author_id, b.title, a.username, a.password, a.email, a.bio" + - " FROM blog b" + - " INNER JOIN author a ON b.author_id = a.id" + - " WHERE b.id = ?"); + final SqlSource sqlSource = new StaticSqlSource(config, + "SELECT b.id, b.author_id, b.title, a.username, a.password, a.email, a.bio" + " FROM blog b" + + " INNER JOIN author a ON b.author_id = a.id" + " WHERE b.id = ?"); final ParameterMap parameterMap = new ParameterMap.Builder(config, "defaultParameterMap", int.class, new ArrayList() { { add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build()); } }).build(); - final ResultMap resultMap = new ResultMap.Builder(config, "defaultResultMap", Blog.class, new ArrayList() { - { - add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class)) - .flags(new ArrayList() { - { - add(ResultFlag.ID); - } - }).build()); - add(new ResultMapping.Builder(config, "title", "title", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "author.id", "author_id", registry.getTypeHandler(int.class)).build()); - add(new ResultMapping.Builder(config, "author.username", "username", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "author.password", "password", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "author.email", "email", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "author.bio", "bio", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "posts", "id", registry.getTypeHandler(int.class)).javaType(List.class).nestedQueryId("selectPostsForBlog").build()); - } - }).build(); + final ResultMap resultMap = new ResultMap.Builder(config, "defaultResultMap", Blog.class, + new ArrayList() { + { + add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class)) + .flags(new ArrayList() { + { + add(ResultFlag.ID); + } + }).build()); + add(new ResultMapping.Builder(config, "title", "title", registry.getTypeHandler(String.class)).build()); + add(new ResultMapping.Builder(config, "author.id", "author_id", registry.getTypeHandler(int.class)) + .build()); + add(new ResultMapping.Builder(config, "author.username", "username", registry.getTypeHandler(String.class)) + .build()); + add(new ResultMapping.Builder(config, "author.password", "password", registry.getTypeHandler(String.class)) + .build()); + add(new ResultMapping.Builder(config, "author.email", "email", registry.getTypeHandler(String.class)) + .build()); + add(new ResultMapping.Builder(config, "author.bio", "bio", registry.getTypeHandler(String.class)).build()); + add(new ResultMapping.Builder(config, "posts", "id", registry.getTypeHandler(int.class)) + .javaType(List.class).nestedQueryId("selectPostsForBlog").build()); + } + }).build(); return new MappedStatement.Builder(config, "selectBlogById", sqlSource, SqlCommandType.SELECT) - .parameterMap(parameterMap) - .resultMaps(new ArrayList() { + .parameterMap(parameterMap).resultMaps(new ArrayList() { { add(resultMap); } @@ -375,10 +393,9 @@ static MappedStatement prepareComplexSelectBlogMappedStatement(final Configurati static MappedStatement prepareSelectBlogByIdAndAuthor(final Configuration config) { final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - final SqlSource sqlSource = new StaticSqlSource(config,"SELECT b.id, b.author_id, b.title, a.username, a.password, a.email, a.bio" + - " FROM blog b" + - " INNER JOIN author a ON b.author_id = a.id" + - " WHERE b.id = ? and a.id = ?"); + final SqlSource sqlSource = new StaticSqlSource(config, + "SELECT b.id, b.author_id, b.title, a.username, a.password, a.email, a.bio" + " FROM blog b" + + " INNER JOIN author a ON b.author_id = a.id" + " WHERE b.id = ? and a.id = ?"); final ParameterMap parameterMap = new ParameterMap.Builder(config, "defaultParameterMap", Map.class, new ArrayList() { { @@ -386,27 +403,32 @@ static MappedStatement prepareSelectBlogByIdAndAuthor(final Configuration config add(new ParameterMapping.Builder(config, "authorId", registry.getTypeHandler(int.class)).build()); } }).build(); - final ResultMap resultMap = new ResultMap.Builder(config, "defaultResultMap", Blog.class, new ArrayList() { - { - add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class)) - .flags(new ArrayList() { - { - add(ResultFlag.ID); - } - }).build()); - add(new ResultMapping.Builder(config, "title", "title", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "author.id", "author_id", registry.getTypeHandler(int.class)).build()); - add(new ResultMapping.Builder(config, "author.username", "username", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "author.password", "password", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "author.email", "email", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "author.bio", "bio", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "posts", "id", registry.getTypeHandler(int.class)).javaType(List.class).nestedQueryId("selectPostsForBlog").build()); - } - }).build(); + final ResultMap resultMap = new ResultMap.Builder(config, "defaultResultMap", Blog.class, + new ArrayList() { + { + add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class)) + .flags(new ArrayList() { + { + add(ResultFlag.ID); + } + }).build()); + add(new ResultMapping.Builder(config, "title", "title", registry.getTypeHandler(String.class)).build()); + add(new ResultMapping.Builder(config, "author.id", "author_id", registry.getTypeHandler(int.class)) + .build()); + add(new ResultMapping.Builder(config, "author.username", "username", registry.getTypeHandler(String.class)) + .build()); + add(new ResultMapping.Builder(config, "author.password", "password", registry.getTypeHandler(String.class)) + .build()); + add(new ResultMapping.Builder(config, "author.email", "email", registry.getTypeHandler(String.class)) + .build()); + add(new ResultMapping.Builder(config, "author.bio", "bio", registry.getTypeHandler(String.class)).build()); + add(new ResultMapping.Builder(config, "posts", "id", registry.getTypeHandler(int.class)) + .javaType(List.class).nestedQueryId("selectPostsForBlog").build()); + } + }).build(); return new MappedStatement.Builder(config, "selectBlogByIdAndAuthor", sqlSource, SqlCommandType.SELECT) - .parameterMap(parameterMap) - .resultMaps(new ArrayList() { + .parameterMap(parameterMap).resultMaps(new ArrayList() { { add(resultMap); } @@ -416,64 +438,68 @@ static MappedStatement prepareSelectBlogByIdAndAuthor(final Configuration config static MappedStatement prepareSelectPostsForBlogMappedStatement(final Configuration config) { final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - final SqlSource sqlSource = new StaticSqlSource(config,"SELECT p.id, p.created_on, p.blog_id, p.section, p.subject, p.body, pt.tag_id," + - " t.name as tag_name, c.id as comment_id, c.name as comment_name, c.comment" + - " FROM post p" + - " INNER JOIN post_tag pt ON pt.post_id = p.id" + - " INNER JOIN tag t ON pt.tag_id = t.id" + - " LEFT OUTER JOIN comment c ON c.post_id = p.id" + - " WHERE p.blog_id = ?"); + final SqlSource sqlSource = new StaticSqlSource(config, + "SELECT p.id, p.created_on, p.blog_id, p.section, p.subject, p.body, pt.tag_id," + + " t.name as tag_name, c.id as comment_id, c.name as comment_name, c.comment" + " FROM post p" + + " INNER JOIN post_tag pt ON pt.post_id = p.id" + " INNER JOIN tag t ON pt.tag_id = t.id" + + " LEFT OUTER JOIN comment c ON c.post_id = p.id" + " WHERE p.blog_id = ?"); final ParameterMap parameterMap = new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList() { { add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build()); } }).build(); - final ResultMap tagResultMap = new ResultMap.Builder(config, "tagResultMap", Tag.class, new ArrayList() { - { - add(new ResultMapping.Builder(config, "id", "tag_id", registry.getTypeHandler(int.class)) - .flags(new ArrayList() { - { - add(ResultFlag.ID); - } - }).build()); - add(new ResultMapping.Builder(config, "name", "tag_name", registry.getTypeHandler(String.class)).build()); - } - }).build(); - final ResultMap commentResultMap = new ResultMap.Builder(config, "commentResultMap", Comment.class, new ArrayList() { - { - add(new ResultMapping.Builder(config, "id", "comment_id", registry.getTypeHandler(int.class)) - .flags(new ArrayList() { - { - add(ResultFlag.ID); - } - }).build()); - add(new ResultMapping.Builder(config, "name", "comment_name", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "comment", "comment", registry.getTypeHandler(String.class)).build()); - } - }).build(); + final ResultMap tagResultMap = new ResultMap.Builder(config, "tagResultMap", Tag.class, + new ArrayList() { + { + add(new ResultMapping.Builder(config, "id", "tag_id", registry.getTypeHandler(int.class)) + .flags(new ArrayList() { + { + add(ResultFlag.ID); + } + }).build()); + add(new ResultMapping.Builder(config, "name", "tag_name", registry.getTypeHandler(String.class)).build()); + } + }).build(); + final ResultMap commentResultMap = new ResultMap.Builder(config, "commentResultMap", Comment.class, + new ArrayList() { + { + add(new ResultMapping.Builder(config, "id", "comment_id", registry.getTypeHandler(int.class)) + .flags(new ArrayList() { + { + add(ResultFlag.ID); + } + }).build()); + add(new ResultMapping.Builder(config, "name", "comment_name", registry.getTypeHandler(String.class)) + .build()); + add(new ResultMapping.Builder(config, "comment", "comment", registry.getTypeHandler(String.class)).build()); + } + }).build(); config.addResultMap(tagResultMap); config.addResultMap(commentResultMap); - final ResultMap postResultMap = new ResultMap.Builder(config, "defaultResultMap", Post.class, new ArrayList() { - { - add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class)) - .flags(new ArrayList() { - { - add(ResultFlag.ID); - } - }).build()); - add(new ResultMapping.Builder(config, "blog", "blog_id", registry.getTypeHandler(int.class)).javaType(Blog.class).nestedQueryId("selectBlogById").build()); - add(new ResultMapping.Builder(config, "createdOn", "created_on", registry.getTypeHandler(Date.class)).build()); - add(new ResultMapping.Builder(config, "section", "section", registry.getTypeHandler(Section.class)).build()); - add(new ResultMapping.Builder(config, "subject", "subject", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "body", "body", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "tags").nestedResultMapId(tagResultMap.getId()).build()); - add(new ResultMapping.Builder(config, "comments").nestedResultMapId(commentResultMap.getId()).build()); - } - }).build(); + final ResultMap postResultMap = new ResultMap.Builder(config, "defaultResultMap", Post.class, + new ArrayList() { + { + add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class)) + .flags(new ArrayList() { + { + add(ResultFlag.ID); + } + }).build()); + add(new ResultMapping.Builder(config, "blog", "blog_id", registry.getTypeHandler(int.class)) + .javaType(Blog.class).nestedQueryId("selectBlogById").build()); + add(new ResultMapping.Builder(config, "createdOn", "created_on", registry.getTypeHandler(Date.class)) + .build()); + add(new ResultMapping.Builder(config, "section", "section", registry.getTypeHandler(Section.class)) + .build()); + add(new ResultMapping.Builder(config, "subject", "subject", registry.getTypeHandler(String.class)).build()); + add(new ResultMapping.Builder(config, "body", "body", registry.getTypeHandler(String.class)).build()); + add(new ResultMapping.Builder(config, "tags").nestedResultMapId(tagResultMap.getId()).build()); + add(new ResultMapping.Builder(config, "comments").nestedResultMapId(commentResultMap.getId()).build()); + } + }).build(); return new MappedStatement.Builder(config, "selectPostsForBlog", sqlSource, SqlCommandType.SELECT) - .parameterMap(parameterMap) - .resultMaps(new ArrayList() { + .parameterMap(parameterMap).resultMaps(new ArrayList() { { add(postResultMap); } @@ -482,42 +508,43 @@ static MappedStatement prepareSelectPostsForBlogMappedStatement(final Configurat static MappedStatement prepareSelectPostMappedStatement(final Configuration config) { final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - final SqlSource sqlSource = new StaticSqlSource(config,"SELECT p.id, p.created_on, p.blog_id, p.section, p.subject, p.body, pt.tag_id," + - " t.name as tag_name, c.id as comment_id, c.name as comment_name, c.comment" + - " FROM post p" + - " LEFT OUTER JOIN post_tag pt ON pt.post_id = p.id" + - " LEFT OUTER JOIN tag t ON pt.tag_id = t.id" + - " LEFT OUTER JOIN comment c ON c.post_id = p.id" + - " WHERE p.id = ?"); + final SqlSource sqlSource = new StaticSqlSource(config, + "SELECT p.id, p.created_on, p.blog_id, p.section, p.subject, p.body, pt.tag_id," + + " t.name as tag_name, c.id as comment_id, c.name as comment_name, c.comment" + " FROM post p" + + " LEFT OUTER JOIN post_tag pt ON pt.post_id = p.id" + " LEFT OUTER JOIN tag t ON pt.tag_id = t.id" + + " LEFT OUTER JOIN comment c ON c.post_id = p.id" + " WHERE p.id = ?"); final ParameterMap parameterMap = new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList() { { add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build()); } }).build(); - final ResultMap tagResultMap = new ResultMap.Builder(config, "tagResultMap", Tag.class, new ArrayList() { - { - add(new ResultMapping.Builder(config, "id", "tag_id", registry.getTypeHandler(int.class)) - .flags(new ArrayList() { - { - add(ResultFlag.ID); - } - }).build()); - add(new ResultMapping.Builder(config, "name", "tag_name", registry.getTypeHandler(String.class)).build()); - } - }).build(); - final ResultMap commentResultMap = new ResultMap.Builder(config, "commentResultMap", Comment.class, new ArrayList() { - { - add(new ResultMapping.Builder(config, "id", "comment_id", registry.getTypeHandler(int.class)) - .flags(new ArrayList() { - { - add(ResultFlag.ID); - } - }).build()); - add(new ResultMapping.Builder(config, "name", "comment_name", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "comment", "comment", registry.getTypeHandler(String.class)).build()); - } - }).build(); + final ResultMap tagResultMap = new ResultMap.Builder(config, "tagResultMap", Tag.class, + new ArrayList() { + { + add(new ResultMapping.Builder(config, "id", "tag_id", registry.getTypeHandler(int.class)) + .flags(new ArrayList() { + { + add(ResultFlag.ID); + } + }).build()); + add(new ResultMapping.Builder(config, "name", "tag_name", registry.getTypeHandler(String.class)).build()); + } + }).build(); + final ResultMap commentResultMap = new ResultMap.Builder(config, "commentResultMap", Comment.class, + new ArrayList() { + { + add(new ResultMapping.Builder(config, "id", "comment_id", registry.getTypeHandler(int.class)) + .flags(new ArrayList() { + { + add(ResultFlag.ID); + } + }).build()); + add(new ResultMapping.Builder(config, "name", "comment_name", registry.getTypeHandler(String.class)) + .build()); + add(new ResultMapping.Builder(config, "comment", "comment", registry.getTypeHandler(String.class)).build()); + } + }).build(); config.addResultMap(tagResultMap); config.addResultMap(commentResultMap); final ResultMap postResultMap = new ResultMap.Builder(config, "", Post.class, new ArrayList() { @@ -528,7 +555,8 @@ static MappedStatement prepareSelectPostMappedStatement(final Configuration conf add(ResultFlag.ID); } }).build()); - add(new ResultMapping.Builder(config, "blog", "blog_id", registry.getTypeHandler(int.class)).javaType(Blog.class).nestedQueryId("selectBlogById").build()); + add(new ResultMapping.Builder(config, "blog", "blog_id", registry.getTypeHandler(int.class)) + .javaType(Blog.class).nestedQueryId("selectBlogById").build()); add(new ResultMapping.Builder(config, "createdOn", "created_on", registry.getTypeHandler(Date.class)).build()); add(new ResultMapping.Builder(config, "section", "section", registry.getTypeHandler(Section.class)).build()); add(new ResultMapping.Builder(config, "subject", "subject", registry.getTypeHandler(String.class)).build()); @@ -538,123 +566,120 @@ static MappedStatement prepareSelectPostMappedStatement(final Configuration conf } }).build(); - return new MappedStatement.Builder(config, "selectPostsForBlog", sqlSource, SqlCommandType.SELECT) - .parameterMap(parameterMap) - .resultMaps(new ArrayList() { + .parameterMap(parameterMap).resultMaps(new ArrayList() { { add(postResultMap); } }).build(); } - static MappedStatement prepareSelectPostWithBlogByAuthorMappedStatement(final Configuration config) { final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - final SqlSource sqlSource = new StaticSqlSource(config,"SELECT p.id, p.created_on, p.blog_id, p.author_id, p.section, p.subject, p.body, pt.tag_id," + - " t.name as tag_name, c.id as comment_id, c.name as comment_name, c.comment" + - " FROM post p" + - " LEFT OUTER JOIN post_tag pt ON pt.post_id = p.id" + - " LEFT OUTER JOIN tag t ON pt.tag_id = t.id" + - " LEFT OUTER JOIN comment c ON c.post_id = p.id" + - " WHERE p.id = ?"); + final SqlSource sqlSource = new StaticSqlSource(config, + "SELECT p.id, p.created_on, p.blog_id, p.author_id, p.section, p.subject, p.body, pt.tag_id," + + " t.name as tag_name, c.id as comment_id, c.name as comment_name, c.comment" + " FROM post p" + + " LEFT OUTER JOIN post_tag pt ON pt.post_id = p.id" + " LEFT OUTER JOIN tag t ON pt.tag_id = t.id" + + " LEFT OUTER JOIN comment c ON c.post_id = p.id" + " WHERE p.id = ?"); final ParameterMap parameterMap = new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList() { { add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build()); } }).build(); - final ResultMap tagResultMap = new ResultMap.Builder(config, "tagResultMap", Tag.class, new ArrayList() { - { - add(new ResultMapping.Builder(config, "id", "tag_id", registry.getTypeHandler(int.class)) - .flags(new ArrayList() { - { - add(ResultFlag.ID); - } - }).build()); - add(new ResultMapping.Builder(config, "name", "tag_name", registry.getTypeHandler(String.class)).build()); - } - }).build(); - final ResultMap commentResultMap = new ResultMap.Builder(config, "commentResultMap", Comment.class, new ArrayList() { - { - add(new ResultMapping.Builder(config, "id", "comment_id", registry.getTypeHandler(int.class)) - .flags(new ArrayList() { - { - add(ResultFlag.ID); - } - }).build()); - add(new ResultMapping.Builder(config, "name", "comment_name", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "comment", "comment", registry.getTypeHandler(String.class)).build()); - } - }).build(); + final ResultMap tagResultMap = new ResultMap.Builder(config, "tagResultMap", Tag.class, + new ArrayList() { + { + add(new ResultMapping.Builder(config, "id", "tag_id", registry.getTypeHandler(int.class)) + .flags(new ArrayList() { + { + add(ResultFlag.ID); + } + }).build()); + add(new ResultMapping.Builder(config, "name", "tag_name", registry.getTypeHandler(String.class)).build()); + } + }).build(); + final ResultMap commentResultMap = new ResultMap.Builder(config, "commentResultMap", Comment.class, + new ArrayList() { + { + add(new ResultMapping.Builder(config, "id", "comment_id", registry.getTypeHandler(int.class)) + .flags(new ArrayList() { + { + add(ResultFlag.ID); + } + }).build()); + add(new ResultMapping.Builder(config, "name", "comment_name", registry.getTypeHandler(String.class)) + .build()); + add(new ResultMapping.Builder(config, "comment", "comment", registry.getTypeHandler(String.class)).build()); + } + }).build(); config.addResultMap(tagResultMap); config.addResultMap(commentResultMap); - final ResultMap postResultMap = new ResultMap.Builder(config, "postResultMap", Post.class, new ArrayList() { - { - add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class)) - .flags(new ArrayList() { - { - add(ResultFlag.ID); - } - }).build()); - - add(new ResultMapping.Builder(config, "blog").nestedQueryId("selectBlogByIdAndAuthor").composites(new ArrayList() { + final ResultMap postResultMap = new ResultMap.Builder(config, "postResultMap", Post.class, + new ArrayList() { { - add(new ResultMapping.Builder(config, "authorId", "author_id", registry.getTypeHandler(int.class)).build()); - add(new ResultMapping.Builder(config, "blogId", "blog_id", registry.getTypeHandler(int.class)).build()); - } - }).build()); - add(new ResultMapping.Builder(config, "createdOn", "created_on", registry.getTypeHandler(Date.class)).build()); - add(new ResultMapping.Builder(config, "section", "section", registry.getTypeHandler(Section.class)).build()); - add(new ResultMapping.Builder(config, "subject", "subject", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "body", "body", registry.getTypeHandler(String.class)).build()); - add(new ResultMapping.Builder(config, "tags").nestedResultMapId(tagResultMap.getId()).build()); - add(new ResultMapping.Builder(config, "comments").nestedResultMapId(commentResultMap.getId()).build()); - } - }).build(); + add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class)) + .flags(new ArrayList() { + { + add(ResultFlag.ID); + } + }).build()); + add(new ResultMapping.Builder(config, "blog").nestedQueryId("selectBlogByIdAndAuthor") + .composites(new ArrayList() { + { + add(new ResultMapping.Builder(config, "authorId", "author_id", registry.getTypeHandler(int.class)) + .build()); + add(new ResultMapping.Builder(config, "blogId", "blog_id", registry.getTypeHandler(int.class)) + .build()); + } + }).build()); + add(new ResultMapping.Builder(config, "createdOn", "created_on", registry.getTypeHandler(Date.class)) + .build()); + add(new ResultMapping.Builder(config, "section", "section", registry.getTypeHandler(Section.class)) + .build()); + add(new ResultMapping.Builder(config, "subject", "subject", registry.getTypeHandler(String.class)).build()); + add(new ResultMapping.Builder(config, "body", "body", registry.getTypeHandler(String.class)).build()); + add(new ResultMapping.Builder(config, "tags").nestedResultMapId(tagResultMap.getId()).build()); + add(new ResultMapping.Builder(config, "comments").nestedResultMapId(commentResultMap.getId()).build()); + } + }).build(); return new MappedStatement.Builder(config, "selectPostsForBlog", sqlSource, SqlCommandType.SELECT) - .parameterMap(parameterMap) - .resultMaps(new ArrayList() { + .parameterMap(parameterMap).resultMaps(new ArrayList() { { add(postResultMap); } }).build(); } - static MappedStatement prepareInsertAuthorMappedStatementWithBeforeAutoKey(final Configuration config) { final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - final ResultMap rm = new ResultMap.Builder(config, "keyResultMap", Integer.class, new ArrayList<>()) - .build(); + final ResultMap rm = new ResultMap.Builder(config, "keyResultMap", Integer.class, new ArrayList<>()).build(); - MappedStatement kms = new MappedStatement.Builder(config, "insertAuthor!selectKey", new StaticSqlSource(config,"SELECT 123456 as id FROM SYSIBM.SYSDUMMY1"), SqlCommandType.SELECT) - .keyProperty("id") - .resultMaps(new ArrayList() { - { - add(rm); - } - }) - .build(); + MappedStatement kms = new MappedStatement.Builder(config, "insertAuthor!selectKey", + new StaticSqlSource(config, "SELECT 123456 as id FROM SYSIBM.SYSDUMMY1"), SqlCommandType.SELECT) + .keyProperty("id").resultMaps(new ArrayList() { + { + add(rm); + } + }).build(); config.addMappedStatement(kms); - return new MappedStatement.Builder(config, "insertAuthor", new DynamicSqlSource(config, new TextSqlNode("INSERT INTO author (id,username,password,email,bio,favourite_section) values(#{id},#{username},#{password},#{email},#{bio:VARCHAR},#{favouriteSection})")), SqlCommandType.INSERT) - .parameterMap( + return new MappedStatement.Builder(config, "insertAuthor", new DynamicSqlSource(config, new TextSqlNode( + "INSERT INTO author (id,username,password,email,bio,favourite_section) values(#{id},#{username},#{password},#{email},#{bio:VARCHAR},#{favouriteSection})")), + SqlCommandType.INSERT).parameterMap( new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList() { { add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(Integer.class)).build()); add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)).build()); add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)).build()); add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)).build()); - add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).build()); - add(new ParameterMapping.Builder(config, "favouriteSection", registry.getTypeHandler(Section.class)).jdbcType(JdbcType.VARCHAR).build()); + add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)) + .jdbcType(JdbcType.VARCHAR).build()); + add(new ParameterMapping.Builder(config, "favouriteSection", registry.getTypeHandler(Section.class)) + .jdbcType(JdbcType.VARCHAR).build()); } - }).build()) - .cache(authorCache) - .keyGenerator(new SelectKeyGenerator(kms, true)) - .keyProperty("id") - .build(); + }).build()).cache(authorCache).keyGenerator(new SelectKeyGenerator(kms, true)).keyProperty("id").build(); } - } diff --git a/src/test/java/org/apache/ibatis/executor/resultset/DefaultResultSetHandlerTest.java b/src/test/java/org/apache/ibatis/executor/resultset/DefaultResultSetHandlerTest.java index d5444ecbc34..6042d7598e2 100644 --- a/src/test/java/org/apache/ibatis/executor/resultset/DefaultResultSetHandlerTest.java +++ b/src/test/java/org/apache/ibatis/executor/resultset/DefaultResultSetHandlerTest.java @@ -107,8 +107,8 @@ void shouldThrowExceptionWithColumnName() throws Exception { final MappedStatement ms = getMappedStatement(); final RowBounds rowBounds = new RowBounds(0, 100); - final DefaultResultSetHandler defaultResultSetHandler = new DefaultResultSetHandler(null/*executor*/, ms, - null/*parameterHandler*/, null/*resultHandler*/, null/*boundSql*/, rowBounds); + final DefaultResultSetHandler defaultResultSetHandler = new DefaultResultSetHandler(null/* executor */, ms, + null/* parameterHandler */, null/* resultHandler */, null/* boundSql */, rowBounds); final ResultSetWrapper rsw = mock(ResultSetWrapper.class); when(rsw.getResultSet()).thenReturn(mock(ResultSet.class)); @@ -121,8 +121,8 @@ void shouldThrowExceptionWithColumnName() throws Exception { List constructorMappings = Collections.singletonList(resultMapping); try { - defaultResultSetHandler.createParameterizedResultObject(rsw, null/*resultType*/, constructorMappings, - null/*constructorArgTypes*/, null/*constructorArgs*/, null/*columnPrefix*/); + defaultResultSetHandler.createParameterizedResultObject(rsw, null/* resultType */, constructorMappings, + null/* constructorArgTypes */, null/* constructorArgs */, null/* columnPrefix */); Assertions.fail("Should have thrown ExecutorException"); } catch (Exception e) { Assertions.assertTrue(e instanceof ExecutorException, "Expected ExecutorException"); @@ -133,12 +133,13 @@ void shouldThrowExceptionWithColumnName() throws Exception { MappedStatement getMappedStatement() { final Configuration config = new Configuration(); final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - return new MappedStatement.Builder(config, "testSelect", new StaticSqlSource(config, "some select statement"), SqlCommandType.SELECT).resultMaps( - new ArrayList() { + return new MappedStatement.Builder(config, "testSelect", new StaticSqlSource(config, "some select statement"), + SqlCommandType.SELECT).resultMaps(new ArrayList() { { add(new ResultMap.Builder(config, "testMap", HashMap.class, new ArrayList() { { - add(new ResultMapping.Builder(config, "cOlUmN1", "CoLuMn1", registry.getTypeHandler(Integer.class)).build()); + add(new ResultMapping.Builder(config, "cOlUmN1", "CoLuMn1", registry.getTypeHandler(Integer.class)) + .build()); } }).build()); } diff --git a/src/test/java/org/apache/ibatis/executor/resultset/DefaultResultSetHandlerTest2.java b/src/test/java/org/apache/ibatis/executor/resultset/DefaultResultSetHandlerTest2.java index e7cd110374c..e0ec8534325 100644 --- a/src/test/java/org/apache/ibatis/executor/resultset/DefaultResultSetHandlerTest2.java +++ b/src/test/java/org/apache/ibatis/executor/resultset/DefaultResultSetHandlerTest2.java @@ -68,16 +68,16 @@ void shouldNotCallNextOnClosedResultSet_SimpleResult() throws Exception { final Configuration config = new Configuration(); final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); final MappedStatement ms = new MappedStatement.Builder(config, "testSelect", - new StaticSqlSource(config, "some select statement"), SqlCommandType.SELECT).resultMaps( - new ArrayList() { - { - add(new ResultMap.Builder(config, "testMap", HashMap.class, new ArrayList() { + new StaticSqlSource(config, "some select statement"), SqlCommandType.SELECT) + .resultMaps(new ArrayList() { { - add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(Integer.class)).build()); + add(new ResultMap.Builder(config, "testMap", HashMap.class, new ArrayList() { + { + add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(Integer.class)).build()); + } + }).build()); } - }).build()); - } - }).build(); + }).build(); final Executor executor = null; final ParameterHandler parameterHandler = null; @@ -85,7 +85,7 @@ void shouldNotCallNextOnClosedResultSet_SimpleResult() throws Exception { final BoundSql boundSql = null; final RowBounds rowBounds = new RowBounds(5, 1); final DefaultResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, ms, parameterHandler, - resultHandler, boundSql, rowBounds); + resultHandler, boundSql, rowBounds); when(stmt.getResultSet()).thenReturn(rs); when(rsmd.getColumnCount()).thenReturn(1); @@ -106,29 +106,23 @@ void shouldNotCallNextOnClosedResultSet_NestedResult() throws Exception { final Configuration config = new Configuration(); final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); final ResultMap nestedResultMap = new ResultMap.Builder(config, "roleMap", HashMap.class, - new ArrayList() { - { - add(new ResultMapping.Builder(config, "role", "role", registry.getTypeHandler(String.class)) - .build()); - } - }).build(); + new ArrayList() { + { + add(new ResultMapping.Builder(config, "role", "role", registry.getTypeHandler(String.class)).build()); + } + }).build(); config.addResultMap(nestedResultMap); final MappedStatement ms = new MappedStatement.Builder(config, "selectPerson", - new StaticSqlSource(config, "select person..."), - SqlCommandType.SELECT).resultMaps( - new ArrayList() { + new StaticSqlSource(config, "select person..."), SqlCommandType.SELECT).resultMaps(new ArrayList() { { add(new ResultMap.Builder(config, "personMap", HashMap.class, new ArrayList() { { - add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(Integer.class)) - .build()); + add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(Integer.class)).build()); add(new ResultMapping.Builder(config, "roles").nestedResultMapId("roleMap").build()); } }).build()); } - }) - .resultOrdered(true) - .build(); + }).resultOrdered(true).build(); final Executor executor = null; final ParameterHandler parameterHandler = null; diff --git a/src/test/java/org/apache/ibatis/mapping/ResultMappingTest.java b/src/test/java/org/apache/ibatis/mapping/ResultMappingTest.java index 20c3d1c773a..86407988a11 100644 --- a/src/test/java/org/apache/ibatis/mapping/ResultMappingTest.java +++ b/src/test/java/org/apache/ibatis/mapping/ResultMappingTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -31,19 +31,16 @@ class ResultMappingTest { @Test void shouldThrowErrorWhenBothResultMapAndNestedSelectAreSet() { Assertions.assertThrows(IllegalStateException.class, () -> { - new ResultMapping.Builder(configuration, "prop") - .nestedQueryId("nested query ID") - .nestedResultMapId("nested resultMap") - .build(); + new ResultMapping.Builder(configuration, "prop").nestedQueryId("nested query ID") + .nestedResultMapId("nested resultMap").build(); }); } - //Issue 4: column is mandatory on nested queries + // Issue 4: column is mandatory on nested queries @Test void shouldFailWithAMissingColumnInNetstedSelect() { - Assertions.assertThrows(IllegalStateException.class, () -> new ResultMapping.Builder(configuration, "prop") - .nestedQueryId("nested query ID") - .build()); + Assertions.assertThrows(IllegalStateException.class, + () -> new ResultMapping.Builder(configuration, "prop").nestedQueryId("nested query ID").build()); } } diff --git a/src/test/java/org/apache/ibatis/scripting/defaults/DefaultParameterHandlerTest.java b/src/test/java/org/apache/ibatis/scripting/defaults/DefaultParameterHandlerTest.java index 3846e307588..c2ec2d052e0 100644 --- a/src/test/java/org/apache/ibatis/scripting/defaults/DefaultParameterHandlerTest.java +++ b/src/test/java/org/apache/ibatis/scripting/defaults/DefaultParameterHandlerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -52,12 +52,15 @@ void setParametersThrowsProperException() throws SQLException { final BoundSql boundSql = mock(BoundSql.class); TypeHandler typeHandler = mock(TypeHandler.class); - doThrow(new SQLException("foo")).when(typeHandler).setParameter(any(PreparedStatement.class), anyInt(), any(), any(JdbcType.class)); - ParameterMapping parameterMapping = new ParameterMapping.Builder(mappedStatement.getConfiguration(), "prop", typeHandler).build(); + doThrow(new SQLException("foo")).when(typeHandler).setParameter(any(PreparedStatement.class), anyInt(), any(), + any(JdbcType.class)); + ParameterMapping parameterMapping = new ParameterMapping.Builder(mappedStatement.getConfiguration(), "prop", + typeHandler).build(); List parameterMappings = Collections.singletonList(parameterMapping); when(boundSql.getParameterMappings()).thenReturn(parameterMappings); - DefaultParameterHandler defaultParameterHandler = new DefaultParameterHandler(mappedStatement, parameterObject, boundSql); + DefaultParameterHandler defaultParameterHandler = new DefaultParameterHandler(mappedStatement, parameterObject, + boundSql); PreparedStatement ps = mock(PreparedStatement.class); try { @@ -73,12 +76,13 @@ void setParametersThrowsProperException() throws SQLException { MappedStatement getMappedStatement() { final Configuration config = new Configuration(); final TypeHandlerRegistry registry = config.getTypeHandlerRegistry(); - return new MappedStatement.Builder(config, "testSelect", new StaticSqlSource(config, "some select statement"), SqlCommandType.SELECT).resultMaps( - new ArrayList() { + return new MappedStatement.Builder(config, "testSelect", new StaticSqlSource(config, "some select statement"), + SqlCommandType.SELECT).resultMaps(new ArrayList() { { add(new ResultMap.Builder(config, "testMap", HashMap.class, new ArrayList() { { - add(new ResultMapping.Builder(config, "cOlUmN1", "CoLuMn1", registry.getTypeHandler(Integer.class)).build()); + add(new ResultMapping.Builder(config, "cOlUmN1", "CoLuMn1", registry.getTypeHandler(Integer.class)) + .build()); } }).build()); } diff --git a/src/test/java/org/apache/ibatis/session/AutoMappingUnknownColumnBehaviorTest.java b/src/test/java/org/apache/ibatis/session/AutoMappingUnknownColumnBehaviorTest.java index a9cbb27f338..e1f27c78fb5 100644 --- a/src/test/java/org/apache/ibatis/session/AutoMappingUnknownColumnBehaviorTest.java +++ b/src/test/java/org/apache/ibatis/session/AutoMappingUnknownColumnBehaviorTest.java @@ -38,104 +38,111 @@ * Tests for specify the behavior when detects an unknown column (or unknown property type) of automatic mapping target. * * @since 3.4.0 + * * @author Kazuki Shimizu */ class AutoMappingUnknownColumnBehaviorTest { - interface Mapper { - @Select({ - "SELECT ", - " ID,", - " USERNAME as USERNAMEEEE,", // unknown column - " PASSWORD,", - " EMAIL,", - " BIO", - "FROM AUTHOR WHERE ID = #{id}"}) - Author selectAuthor(int id); - - @Select({ - "SELECT ", - " ID,", // unknown property type - " USERNAME", - "FROM AUTHOR WHERE ID = #{id}"}) - SimpleAuthor selectSimpleAuthor(int id); + // @formatter:off + interface Mapper { + @Select({ + "SELECT ", + " ID,", + " USERNAME as USERNAMEEEE,", // unknown column + " PASSWORD,", + " EMAIL,", + " BIO", + "FROM AUTHOR WHERE ID = #{id}" + }) + Author selectAuthor(int id); + + @Select({ + "SELECT ", + " ID,", // unknown property type + " USERNAME", + "FROM AUTHOR WHERE ID = #{id}" + }) + SimpleAuthor selectSimpleAuthor(int id); + } + // @formatter:on + + static class SimpleAuthor { + private AtomicInteger id; // unknown property type + private String username; + + public AtomicInteger getId() { + return id; } - static class SimpleAuthor { - private AtomicInteger id; // unknown property type - private String username; - - public AtomicInteger getId() { - return id; - } - - public void setId(AtomicInteger id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } + public void setId(AtomicInteger id) { + this.id = id; } - public static class LastEventSavedAppender extends UnsynchronizedAppenderBase { - private static ILoggingEvent lastEvent; + public String getUsername() { + return username; + } - @Override - protected void append(ILoggingEvent event) { - lastEvent = event; - } + public void setUsername(String username) { + this.username = username; } + } - private static SqlSessionFactory sqlSessionFactory; + public static class LastEventSavedAppender extends UnsynchronizedAppenderBase { + private static ILoggingEvent lastEvent; - @BeforeAll - static void setup() throws Exception { - DataSource dataSource = BaseDataTest.createBlogDataSource(); - TransactionFactory transactionFactory = new JdbcTransactionFactory(); - Environment environment = new Environment("Production", transactionFactory, dataSource); - Configuration configuration = new Configuration(environment); - configuration.addMapper(Mapper.class); - sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); + @Override + protected void append(ILoggingEvent event) { + lastEvent = event; } - - @Test - void none() { - sqlSessionFactory.getConfiguration().setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.NONE); - try (SqlSession session = sqlSessionFactory.openSession()) { - Mapper mapper = session.getMapper(Mapper.class); - Author author = mapper.selectAuthor(101); - assertThat(author.getId()).isEqualTo(101); - assertThat(author.getUsername()).isNull(); - } + } + + private static SqlSessionFactory sqlSessionFactory; + + @BeforeAll + static void setup() throws Exception { + DataSource dataSource = BaseDataTest.createBlogDataSource(); + TransactionFactory transactionFactory = new JdbcTransactionFactory(); + Environment environment = new Environment("Production", transactionFactory, dataSource); + Configuration configuration = new Configuration(environment); + configuration.addMapper(Mapper.class); + sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); + } + + @Test + void none() { + sqlSessionFactory.getConfiguration().setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.NONE); + try (SqlSession session = sqlSessionFactory.openSession()) { + Mapper mapper = session.getMapper(Mapper.class); + Author author = mapper.selectAuthor(101); + assertThat(author.getId()).isEqualTo(101); + assertThat(author.getUsername()).isNull(); } - - @Test - void warningCauseByUnknownPropertyType() { - sqlSessionFactory.getConfiguration().setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.WARNING); - try (SqlSession session = sqlSessionFactory.openSession()) { - Mapper mapper = session.getMapper(Mapper.class); - SimpleAuthor author = mapper.selectSimpleAuthor(101); - assertThat(author.getId()).isNull(); - assertThat(author.getUsername()).isEqualTo("jim"); - assertThat(LastEventSavedAppender.lastEvent.getMessage()).isEqualTo("Unknown column is detected on 'org.apache.ibatis.session.AutoMappingUnknownColumnBehaviorTest$Mapper.selectSimpleAuthor' auto-mapping. Mapping parameters are [columnName=ID,propertyName=id,propertyType=java.util.concurrent.atomic.AtomicInteger]"); - } + } + + @Test + void warningCauseByUnknownPropertyType() { + sqlSessionFactory.getConfiguration().setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.WARNING); + try (SqlSession session = sqlSessionFactory.openSession()) { + Mapper mapper = session.getMapper(Mapper.class); + SimpleAuthor author = mapper.selectSimpleAuthor(101); + assertThat(author.getId()).isNull(); + assertThat(author.getUsername()).isEqualTo("jim"); + assertThat(LastEventSavedAppender.lastEvent.getMessage()).isEqualTo( + "Unknown column is detected on 'org.apache.ibatis.session.AutoMappingUnknownColumnBehaviorTest$Mapper.selectSimpleAuthor' auto-mapping. Mapping parameters are [columnName=ID,propertyName=id,propertyType=java.util.concurrent.atomic.AtomicInteger]"); } - - @Test - void failingCauseByUnknownColumn() { - sqlSessionFactory.getConfiguration().setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.FAILING); - try (SqlSession session = sqlSessionFactory.openSession()) { - Mapper mapper = session.getMapper(Mapper.class); - mapper.selectAuthor(101); - } catch (PersistenceException e) { - assertThat(e.getCause()).isInstanceOf(SqlSessionException.class); - assertThat(e.getCause().getMessage()).isEqualTo("Unknown column is detected on 'org.apache.ibatis.session.AutoMappingUnknownColumnBehaviorTest$Mapper.selectAuthor' auto-mapping. Mapping parameters are [columnName=USERNAMEEEE,propertyName=USERNAMEEEE,propertyType=null]"); - } + } + + @Test + void failingCauseByUnknownColumn() { + sqlSessionFactory.getConfiguration().setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.FAILING); + try (SqlSession session = sqlSessionFactory.openSession()) { + Mapper mapper = session.getMapper(Mapper.class); + mapper.selectAuthor(101); + } catch (PersistenceException e) { + assertThat(e.getCause()).isInstanceOf(SqlSessionException.class); + assertThat(e.getCause().getMessage()).isEqualTo( + "Unknown column is detected on 'org.apache.ibatis.session.AutoMappingUnknownColumnBehaviorTest$Mapper.selectAuthor' auto-mapping. Mapping parameters are [columnName=USERNAMEEEE,propertyName=USERNAMEEEE,propertyType=null]"); } + } } diff --git a/src/test/java/org/apache/ibatis/submitted/member_access/MemberAccessTest.java b/src/test/java/org/apache/ibatis/submitted/member_access/MemberAccessTest.java index 0cf72b5cd74..3d32f1355ab 100644 --- a/src/test/java/org/apache/ibatis/submitted/member_access/MemberAccessTest.java +++ b/src/test/java/org/apache/ibatis/submitted/member_access/MemberAccessTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -183,56 +183,55 @@ void constructorMapping() { } interface Mapper { + // @formatter:off @Select({ - // @formatter:off - "SELECT" - ,"#{privateField} as privateField" - ,",#{packagePrivateField} as packagePrivateField" - ,",#{protectedField} as protectedField" - ,",#{publicField} as publicField" - ,",#{privateProperty} as privateProperty" - ,",#{packagePrivateProperty} as packagePrivateProperty" - ,",#{protectedProperty} as protectedProperty" - ,",#{publicProperty} as publicProperty" - ,"FROM" - ,"INFORMATION_SCHEMA.SYSTEM_USERS" - // @formatter:on + "SELECT" + , "#{privateField} as privateField" + , ",#{packagePrivateField} as packagePrivateField" + , ",#{protectedField} as protectedField" + , ",#{publicField} as publicField" + , ",#{privateProperty} as privateProperty" + , ",#{packagePrivateProperty} as packagePrivateProperty" + , ",#{protectedProperty} as protectedProperty" + , ",#{publicProperty} as publicProperty" + , "FROM" + , "INFORMATION_SCHEMA.SYSTEM_USERS" }) + // @formatter:on Bean resultAutoMapping(Params params); + // @formatter:off @Select({ - // @formatter:off ""} - // @formatter:on ) + // @formatter:on Bean resultAutoMappingUsingOgnl(Params params); + // @formatter:off @Results({ - // @formatter:off @Result(property = "privateField", column = "private_field") ,@Result(property = "packagePrivateField", column = "package_private_field") ,@Result(property = "protectedField", column = "protected_field") @@ -241,23 +240,20 @@ interface Mapper { ,@Result(property = "packagePrivateProperty", column = "package_private_property") ,@Result(property = "protectedProperty", column = "protected_property") ,@Result(property = "publicProperty", column = "public_property") - // @formatter:on }) @Select({ - // @formatter:off - "SELECT" - ,"#{privateField} as private_field" - ,",#{packagePrivateField} as package_private_field" - ,",#{protectedField} as protected_field" - ,",#{publicField} as public_field" - ,",#{privateProperty} as private_property" - ,",#{packagePrivateProperty} as package_private_property" - ,",#{protectedProperty} as protected_property" - ,",#{publicProperty} as public_property" - ,"FROM" - ,"INFORMATION_SCHEMA.SYSTEM_USERS" - // @formatter:on + "SELECT" + , "#{privateField} as private_field" + , ",#{packagePrivateField} as package_private_field" + , ",#{protectedField} as protected_field" + , ",#{publicField} as public_field" + , ",#{privateProperty} as private_property" + , ",#{packagePrivateProperty} as package_private_property" + , ",#{protectedProperty} as protected_property" + , ",#{publicProperty} as public_property" + , "FROM INFORMATION_SCHEMA.SYSTEM_USERS" }) + // @formatter:on Bean resultMapping(Params params); @Select("SELECT '1' FROM INFORMATION_SCHEMA.SYSTEM_USERS") @@ -276,33 +272,33 @@ interface Mapper { @Select("SELECT '1' as c1 FROM INFORMATION_SCHEMA.SYSTEM_USERS") Immutable privateConstructorMapping(); + // @formatter:off @ConstructorArgs({ - // @formatter:off - @Arg(column = "c1", javaType = String.class) - ,@Arg(column = "c2", javaType = String.class) - // @formatter:on + @Arg(column = "c1", javaType = String.class) + , @Arg(column = "c2", javaType = String.class) }) + // @formatter:on @Select("SELECT '1' as c1, '2' as c2 FROM INFORMATION_SCHEMA.SYSTEM_USERS") Immutable packagePrivateConstructorMapping(); + // @formatter:off @ConstructorArgs({ - // @formatter:off - @Arg(column = "c1", javaType = String.class) - ,@Arg(column = "c2", javaType = String.class) - ,@Arg(column = "c3", javaType = String.class) - // @formatter:on + @Arg(column = "c1", javaType = String.class) + , @Arg(column = "c2", javaType = String.class) + , @Arg(column = "c3", javaType = String.class) }) + // @formatter:on @Select("SELECT '1' as c1, '2' as c2, '3' as c3 FROM INFORMATION_SCHEMA.SYSTEM_USERS") Immutable protectedConstructorMapping(); + // @formatter:off @ConstructorArgs({ - // @formatter:off - @Arg(column = "c1", javaType = String.class) - ,@Arg(column = "c2", javaType = String.class) - ,@Arg(column = "c3", javaType = String.class) - ,@Arg(column = "c4", javaType = String.class) - // @formatter:on + @Arg(column = "c1", javaType = String.class) + , @Arg(column = "c2", javaType = String.class) + , @Arg(column = "c3", javaType = String.class) + , @Arg(column = "c4", javaType = String.class) }) + // @formatter:on @Select("SELECT '1' as c1, '2' as c2, '3' as c3, '4' as c4 FROM INFORMATION_SCHEMA.SYSTEM_USERS") Immutable publicConstructorMapping(); diff --git a/src/test/java/org/apache/ibatis/submitted/named_constructor_args/InvalidNamedConstructorArgsTest.java b/src/test/java/org/apache/ibatis/submitted/named_constructor_args/InvalidNamedConstructorArgsTest.java index 885bb1c0a3c..8dbdceb2660 100644 --- a/src/test/java/org/apache/ibatis/submitted/named_constructor_args/InvalidNamedConstructorArgsTest.java +++ b/src/test/java/org/apache/ibatis/submitted/named_constructor_args/InvalidNamedConstructorArgsTest.java @@ -50,9 +50,11 @@ static void setUp() throws Exception { } interface NoMatchingConstructorMapper { + // @formatter:off @ConstructorArgs({ @Arg(column = "id", name = "noSuchConstructorArg"), - }) + }) + // @formatter:on @Select("select * from users ") User select(); } @@ -62,19 +64,20 @@ void noMatchingConstructorArgName() { Configuration configuration = sqlSessionFactory.getConfiguration(); when(() -> configuration.addMapper(NoMatchingConstructorMapper.class)); - then(caughtException()).isInstanceOf(BuilderException.class) - .hasMessageContaining( - "'org.apache.ibatis.submitted.named_constructor_args.InvalidNamedConstructorArgsTest$NoMatchingConstructorMapper.select-void'") - .hasMessageContaining("'org.apache.ibatis.submitted.named_constructor_args.User'") - .hasMessageContaining("[noSuchConstructorArg]"); + then(caughtException()).isInstanceOf(BuilderException.class).hasMessageContaining( + "'org.apache.ibatis.submitted.named_constructor_args.InvalidNamedConstructorArgsTest$NoMatchingConstructorMapper.select-void'") + .hasMessageContaining("'org.apache.ibatis.submitted.named_constructor_args.User'") + .hasMessageContaining("[noSuchConstructorArg]"); } interface ConstructorWithWrongJavaType { // There is a constructor with arg name 'id', but // its type is different from the specified javaType. + // @formatter:off @ConstructorArgs({ @Arg(column = "id", name = "id", javaType = Integer.class), - }) + }) + // @formatter:on @Select("select * from users ") User select(); } @@ -93,9 +96,11 @@ interface ConstructorMissingRequiresJavaType { // is different from the type of a property with the same name. // javaType is required in this case. // Debug log shows the detail of the matching error. + // @formatter:off @ConstructorArgs({ @Arg(column = "id", name = "id"), - }) + }) + // @formatter:on @Select("select * from users ") User select(); } diff --git a/src/test/java/org/apache/ibatis/submitted/named_constructor_args/Mapper.java b/src/test/java/org/apache/ibatis/submitted/named_constructor_args/Mapper.java index 6eba60a7647..8e9649bdd51 100644 --- a/src/test/java/org/apache/ibatis/submitted/named_constructor_args/Mapper.java +++ b/src/test/java/org/apache/ibatis/submitted/named_constructor_args/Mapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -21,11 +21,13 @@ public interface Mapper { + // @formatter:off @ConstructorArgs({ @Arg(column = "name", name = "name"), @Arg(id = true, column = "id", name = "id"), @Arg(column = "team", name = "team", javaType = String.class), - }) + }) + // @formatter:on @Select("select * from users where id = #{id}") User mapConstructorWithParamAnnos(Integer id); diff --git a/src/test/java/org/apache/ibatis/submitted/named_constructor_args/UseActualNameMapper.java b/src/test/java/org/apache/ibatis/submitted/named_constructor_args/UseActualNameMapper.java index 4bca52027da..c5e4f347adf 100644 --- a/src/test/java/org/apache/ibatis/submitted/named_constructor_args/UseActualNameMapper.java +++ b/src/test/java/org/apache/ibatis/submitted/named_constructor_args/UseActualNameMapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -21,10 +21,12 @@ public interface UseActualNameMapper { + // @formatter:off @ConstructorArgs({ @Arg(column = "name", name = "name"), @Arg(id = true, column = "id", name = "userId", javaType = Integer.class) - }) + }) + // @formatter:on @Select("select * from users where id = #{id}") User mapConstructorWithoutParamAnnos(Integer id); diff --git a/src/test/java/org/apache/ibatis/submitted/param_name_resolve/NoActualParamNameTest.java b/src/test/java/org/apache/ibatis/submitted/param_name_resolve/NoActualParamNameTest.java index 30c8c41a770..96d1b117c0d 100644 --- a/src/test/java/org/apache/ibatis/submitted/param_name_resolve/NoActualParamNameTest.java +++ b/src/test/java/org/apache/ibatis/submitted/param_name_resolve/NoActualParamNameTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -84,34 +84,40 @@ void testSingleListParameterWhenUseActualParamNameIsFalse() { } interface Mapper { + // @formatter:off @Select({ - "" - }) + "" + }) + // @formatter:on Long getUserCountUsingList(List ids); + // @formatter:off @Select({ - "" - }) + "" + }) + // @formatter:on Long getUserCountUsingListWithAliasIsCollection(List ids); + // @formatter:off @Select({ - "" - }) + "" + }) + // @formatter:on Long getUserCountUsingListWithAliasIsList(List ids); } diff --git a/src/test/java/org/apache/ibatis/submitted/record_type/RecordTypeMapper.java b/src/test/java/org/apache/ibatis/submitted/record_type/RecordTypeMapper.java index 2eb564aa159..41b4d558f01 100644 --- a/src/test/java/org/apache/ibatis/submitted/record_type/RecordTypeMapper.java +++ b/src/test/java/org/apache/ibatis/submitted/record_type/RecordTypeMapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -37,10 +37,12 @@ public interface RecordTypeMapper { @Arg(id = true, column = "id", javaType = Integer.class) @Arg(javaType = Property.class, resultMap = "propertyRM", columnPrefix = "p_") + // @formatter:off @Select({ - "select i.id, p.id p_id, p.val p_val, p.url p_url", - "from item i left join prop p on p.id = i.prop_id", - "where i.id = #{id}" }) + "select i.id, p.id p_id, p.val p_val, p.url p_url", + "from item i left join prop p on p.id = i.prop_id", + "where i.id = #{id}" }) + // @formatter:on Item selectItem(Integer id); } diff --git a/src/test/java/org/apache/ibatis/submitted/repeatable/RepeatableErrorTest.java b/src/test/java/org/apache/ibatis/submitted/repeatable/RepeatableErrorTest.java index 22cab9a36e3..84cf32e05cb 100644 --- a/src/test/java/org/apache/ibatis/submitted/repeatable/RepeatableErrorTest.java +++ b/src/test/java/org/apache/ibatis/submitted/repeatable/RepeatableErrorTest.java @@ -31,9 +31,11 @@ class RepeatableErrorTest { void noSuchStatementByCurrentDatabase() throws IOException { try (Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/repeatable/mybatis-config.xml")) { SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader, "development-derby"); - BuilderException exception = Assertions.assertThrows(BuilderException.class, () -> - sqlSessionFactory.getConfiguration().addMapper(NoDefineDefaultDatabaseMapper.class)); - Assertions.assertEquals("Could not find a statement annotation that correspond a current database or default statement on method 'org.apache.ibatis.submitted.repeatable.NoDefineDefaultDatabaseMapper.getUser'. Current database id is [derby].", exception.getMessage()); + BuilderException exception = Assertions.assertThrows(BuilderException.class, + () -> sqlSessionFactory.getConfiguration().addMapper(NoDefineDefaultDatabaseMapper.class)); + Assertions.assertEquals( + "Could not find a statement annotation that correspond a current database or default statement on method 'org.apache.ibatis.submitted.repeatable.NoDefineDefaultDatabaseMapper.getUser'. Current database id is [derby].", + exception.getMessage()); } } diff --git a/src/test/java/org/apache/ibatis/submitted/results_id/Mapper.java b/src/test/java/org/apache/ibatis/submitted/results_id/Mapper.java index 7b6302e05fc..406a84f87ae 100644 --- a/src/test/java/org/apache/ibatis/submitted/results_id/Mapper.java +++ b/src/test/java/org/apache/ibatis/submitted/results_id/Mapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -24,10 +24,12 @@ public interface Mapper { + // @formatter:off @Results(id = "userResult", value = { - @Result(id = true, column = "uid", property = "id"), - @Result(column = "name", property = "name") - }) + @Result(id = true, column = "uid", property = "id"), + @Result(column = "name", property = "name") + }) + // @formatter:on @Select("select * from users where uid = #{id}") User getUserById(Integer id); @@ -36,10 +38,12 @@ public interface Mapper { User getUserByName(String name); @Results(id = "userResultConstructor") + // @formatter:off @ConstructorArgs({ - @Arg(id = true, column = "uid", javaType = Integer.class), - @Arg(column = "name", javaType = String.class) - }) + @Arg(id = true, column = "uid", javaType = Integer.class), + @Arg(column = "name", javaType = String.class) + }) + // @formatter:on @Select("select * from users where uid = #{id}") User getUserByIdConstructor(Integer id); diff --git a/src/test/java/org/apache/ibatis/submitted/sptests/SPMapper.java b/src/test/java/org/apache/ibatis/submitted/sptests/SPMapper.java index bef219bbc70..d51e18e017c 100644 --- a/src/test/java/org/apache/ibatis/submitted/sptests/SPMapper.java +++ b/src/test/java/org/apache/ibatis/submitted/sptests/SPMapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -47,19 +47,22 @@ public interface SPMapper { List getNamesAndItemsLinkedById(int id); - Object echoDate(Map parameter); // issue #145 + Object echoDate(Map parameter); // issue #145 // annotated - @Select({ "{call sptest.adder(", "#{addend1,jdbcType=INTEGER,mode=IN},", "#{addend2,jdbcType=INTEGER,mode=IN},", "#{sum,jdbcType=INTEGER,mode=OUT})}" }) + @Select({ "{call sptest.adder(", "#{addend1,jdbcType=INTEGER,mode=IN},", "#{addend2,jdbcType=INTEGER,mode=IN},", + "#{sum,jdbcType=INTEGER,mode=OUT})}" }) @Options(statementType = StatementType.CALLABLE) Object adderAsSelectAnnotated(Parameter parameter); - @Update({ "{call sptest.adder(", "#{addend1,jdbcType=INTEGER,mode=IN},", "#{addend2,jdbcType=INTEGER,mode=IN},", "#{sum,jdbcType=INTEGER,mode=OUT})}" }) + @Update({ "{call sptest.adder(", "#{addend1,jdbcType=INTEGER,mode=IN},", "#{addend2,jdbcType=INTEGER,mode=IN},", + "#{sum,jdbcType=INTEGER,mode=OUT})}" }) @Options(statementType = StatementType.CALLABLE) void adderAsUpdateAnnotated(Parameter parameter); @Select("{call sptest.getname(#{id,jdbcType=INTEGER,mode=IN})}") - @Results({ @Result(column = "ID", property = "id"), @Result(column = "FIRST_NAME", property = "firstName"), @Result(column = "LAST_NAME", property = "lastName") }) + @Results({ @Result(column = "ID", property = "id"), @Result(column = "FIRST_NAME", property = "firstName"), + @Result(column = "LAST_NAME", property = "lastName") }) @Options(statementType = StatementType.CALLABLE) Name getNameAnnotated(Integer id); @@ -68,27 +71,35 @@ public interface SPMapper { @Options(statementType = StatementType.CALLABLE) Name getNameAnnotatedWithXMLResultMap(Integer id); - @Select({ "{call sptest.getnames(", "#{lowestId,jdbcType=INTEGER,mode=IN},", "#{totalRows,jdbcType=INTEGER,mode=OUT})}" }) - @Results({ @Result(column = "ID", property = "id"), @Result(column = "FIRST_NAME", property = "firstName"), @Result(column = "LAST_NAME", property = "lastName") }) + @Select({ "{call sptest.getnames(", "#{lowestId,jdbcType=INTEGER,mode=IN},", + "#{totalRows,jdbcType=INTEGER,mode=OUT})}" }) + @Results({ @Result(column = "ID", property = "id"), @Result(column = "FIRST_NAME", property = "firstName"), + @Result(column = "LAST_NAME", property = "lastName") }) @Options(statementType = StatementType.CALLABLE) List getNamesAnnotated(Map parms); - @Select({ "{call sptest.getnames(", "#{lowestId,jdbcType=INTEGER,mode=IN},", "#{totalRows,jdbcType=INTEGER,mode=OUT})}" }) + @Select({ "{call sptest.getnames(", "#{lowestId,jdbcType=INTEGER,mode=IN},", + "#{totalRows,jdbcType=INTEGER,mode=OUT})}" }) @ResultMap("nameResult") @Options(statementType = StatementType.CALLABLE) List getNamesAnnotatedWithXMLResultMap(Map parms); - @Select({ "{call sptest.getnamesLowHigh(", "#{lowestId,jdbcType=INTEGER,mode=IN},", "#{highestId,jdbcType=INTEGER,mode=IN})}" }) + @Select({ "{call sptest.getnamesLowHigh(", "#{lowestId,jdbcType=INTEGER,mode=IN},", + "#{highestId,jdbcType=INTEGER,mode=IN})}" }) @ResultMap("nameResult") @Options(statementType = StatementType.CALLABLE) - List getNamesAnnotatedLowHighWithXMLResultMap(@Param("lowestId") int lowestId, @Param("highestId") int highestId); + List getNamesAnnotatedLowHighWithXMLResultMap(@Param("lowestId") int lowestId, + @Param("highestId") int highestId); - @Select({ "{call sptest.arraytest(", "#{ids,mode=IN,jdbcType=ARRAY},", "#{requestedRows,jdbcType=INTEGER,mode=OUT},", "#{returnedIds,mode=OUT,jdbcType=ARRAY})}" }) - @Results({ @Result(column = "ID", property = "id"), @Result(column = "FIRST_NAME", property = "firstName"), @Result(column = "LAST_NAME", property = "lastName") }) + @Select({ "{call sptest.arraytest(", "#{ids,mode=IN,jdbcType=ARRAY},", "#{requestedRows,jdbcType=INTEGER,mode=OUT},", + "#{returnedIds,mode=OUT,jdbcType=ARRAY})}" }) + @Results({ @Result(column = "ID", property = "id"), @Result(column = "FIRST_NAME", property = "firstName"), + @Result(column = "LAST_NAME", property = "lastName") }) @Options(statementType = StatementType.CALLABLE) List getNamesWithArrayAnnotated(Map parms); - @Select({ "{call sptest.arraytest(", "#{ids,mode=IN,jdbcType=ARRAY},", "#{requestedRows,jdbcType=INTEGER,mode=OUT},", "#{returnedIds,mode=OUT,jdbcType=ARRAY})}" }) + @Select({ "{call sptest.arraytest(", "#{ids,mode=IN,jdbcType=ARRAY},", "#{requestedRows,jdbcType=INTEGER,mode=OUT},", + "#{returnedIds,mode=OUT,jdbcType=ARRAY})}" }) @ResultMap("nameResult") @Options(statementType = StatementType.CALLABLE) List getNamesWithArrayAnnotatedWithXMLResultMap(Map parms); diff --git a/src/test/java/org/apache/ibatis/submitted/sptests/SPTest.java b/src/test/java/org/apache/ibatis/submitted/sptests/SPTest.java index d03e0ecc77a..b26fb60f0ae 100644 --- a/src/test/java/org/apache/ibatis/submitted/sptests/SPTest.java +++ b/src/test/java/org/apache/ibatis/submitted/sptests/SPTest.java @@ -661,8 +661,7 @@ void testGetNamesWithArray_a2() throws SQLException { /** * This test shows how to call procedures that return multiple result sets. *

- * This test shows using annotations for stored procedures and referring to multiple - * resultMaps in XML. + * This test shows using annotations for stored procedures and referring to multiple resultMaps in XML. * * @throws SQLException */ diff --git a/src/test/java/org/apache/ibatis/submitted/sql/Mapper.java b/src/test/java/org/apache/ibatis/submitted/sql/Mapper.java index 6635f1a24b7..950da3e9657 100644 --- a/src/test/java/org/apache/ibatis/submitted/sql/Mapper.java +++ b/src/test/java/org/apache/ibatis/submitted/sql/Mapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -29,13 +29,15 @@ public interface Mapper { class SqlProvider implements ProviderMethodResolver { public String findAll() { + // @formatter:off return new SQL() - .SELECT("user_id", "name") - .FROM("${schema}users") - .ORDER_BY("user_id") - .OFFSET_ROWS("#{offset}") - .FETCH_FIRST_ROWS_ONLY("#{limit}") - .toString(); + .SELECT("user_id", "name") + .FROM("${schema}users") + .ORDER_BY("user_id") + .OFFSET_ROWS("#{offset}") + .FETCH_FIRST_ROWS_ONLY("#{limit}") + .toString(); + // @formatter:on } } diff --git a/src/test/java/org/apache/ibatis/submitted/typehandler/Mapper.java b/src/test/java/org/apache/ibatis/submitted/typehandler/Mapper.java index 516dc6b7e87..2f6c1500856 100644 --- a/src/test/java/org/apache/ibatis/submitted/typehandler/Mapper.java +++ b/src/test/java/org/apache/ibatis/submitted/typehandler/Mapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -28,17 +28,17 @@ public interface Mapper { @Select("select * from users where id = #{value}") + // @formatter:off @Results({ - @Result(column="id", property="id"), - @Result(column="name", property="name"), - @Result(column="city", property="city", jdbcType=JdbcType.CHAR), - @Result(column="state", property="state", jdbcType=JdbcType.VARCHAR) - }) + @Result(column = "id", property = "id"), + @Result(column = "name", property = "name"), + @Result(column = "city", property = "city", jdbcType = JdbcType.CHAR), + @Result(column = "state", property = "state", jdbcType = JdbcType.VARCHAR) + }) + // @formatter:on User getUser(Integer id); - @Insert({ - "insert into product (name) values (#{name})" - }) + @Insert({ "insert into product (name) values (#{name})" }) @Options(useGeneratedKeys = true, keyProperty = "id") int insertProduct(Product product); @@ -48,10 +48,12 @@ public interface Mapper { Product getProductByNameXml(String name); @Select("select id, name from product where name = #{value}") + // @formatter:off @ConstructorArgs({ - @Arg(id = true, column="id", javaType = ProductId.class, jdbcType=JdbcType.INTEGER), - @Arg(column="name") - }) + @Arg(id = true, column = "id", javaType = ProductId.class, jdbcType = JdbcType.INTEGER), + @Arg(column = "name") + }) + // @formatter:on Product getProductByNameUsingConstructor(String name); @Select("select id from product where name = #{value}")