Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Support java.util.Optional as return type of mapper method #799

Merged
merged 7 commits into from Mar 16, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 24 additions & 6 deletions src/main/java/org/apache/ibatis/binding/MapperMethod.java
@@ -1,5 +1,5 @@
/**
* Copyright 2009-2017 the original author or authors.
* Copyright 2009-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -21,7 +21,9 @@
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.StatementType;
import org.apache.ibatis.reflection.Jdk;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.OptionalUtil;
import org.apache.ibatis.reflection.ParamNameResolver;
import org.apache.ibatis.reflection.TypeParameterResolver;
import org.apache.ibatis.session.Configuration;
Expand All @@ -39,6 +41,7 @@
* @author Clinton Begin
* @author Eduardo Macarron
* @author Lasse Voss
* @author Kazuki Shimizu
*/
public class MapperMethod {

Expand All @@ -54,7 +57,7 @@ public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
switch (command.getType()) {
case INSERT: {
Object param = method.convertArgsToSqlCommandParam(args);
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.insert(command.getName(), param));
break;
}
Expand All @@ -81,6 +84,10 @@ public Object execute(SqlSession sqlSession, Object[] args) {
} else {
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(command.getName(), param);
if (method.returnsOptional() &&
(result == null || !method.getReturnType().equals(result.getClass()))) {
result = OptionalUtil.ofNullable(result);
}
}
break;
case FLUSH:
Expand Down Expand Up @@ -116,8 +123,8 @@ private void executeWithResultHandler(SqlSession sqlSession, Object[] args) {
MappedStatement ms = sqlSession.getConfiguration().getMappedStatement(command.getName());
if (!StatementType.CALLABLE.equals(ms.getStatementType())
&& void.class.equals(ms.getResultMaps().get(0).getType())) {
throw new BindingException("method " + command.getName()
+ " needs either a @ResultMap annotation, a @ResultType annotation,"
throw new BindingException("method " + command.getName()
+ " needs either a @ResultMap annotation, a @ResultType annotation,"
+ " or a resultType attribute in XML so a ResultHandler can be used as a parameter.");
}
Object param = method.convertArgsToSqlCommandParam(args);
Expand Down Expand Up @@ -176,7 +183,7 @@ private <E> Object convertToArray(List<E> list) {
for (int i = 0; i < list.size(); i++) {
Array.set(array, i, list.get(i));
}
return array;
return array;
} else {
return list.toArray((E[])array);
}
Expand Down Expand Up @@ -219,7 +226,7 @@ public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method
MappedStatement ms = resolveMappedStatement(mapperInterface, methodName, declaringClass,
configuration);
if (ms == null) {
if (method.getAnnotation(Flush.class) != null) {
if(method.getAnnotation(Flush.class) != null){
name = null;
type = SqlCommandType.FLUSH;
} else {
Expand Down Expand Up @@ -270,6 +277,7 @@ public static class MethodSignature {
private final boolean returnsMap;
private final boolean returnsVoid;
private final boolean returnsCursor;
private final boolean returnsOptional;
private final Class<?> returnType;
private final String mapKey;
private final Integer resultHandlerIndex;
Expand All @@ -288,6 +296,7 @@ public MethodSignature(Configuration configuration, Class<?> mapperInterface, Me
this.returnsVoid = void.class.equals(this.returnType);
this.returnsMany = configuration.getObjectFactory().isCollection(this.returnType) || this.returnType.isArray();
this.returnsCursor = Cursor.class.equals(this.returnType);
this.returnsOptional = Jdk.optionalExists && Optional.class.equals(this.returnType);
this.mapKey = getMapKey(method);
this.returnsMap = this.mapKey != null;
this.rowBoundsIndex = getUniqueParamIndex(method, RowBounds.class);
Expand Down Expand Up @@ -339,6 +348,15 @@ public boolean returnsCursor() {
return returnsCursor;
}

/**
* return whether return type is {@code java.util.Optional}
* @return return {@code true}, if return type is {@code java.util.Optional}
* @since 3.4.2
*/
public boolean returnsOptional() {
return returnsOptional;
}

private Integer getUniqueParamIndex(Method method, Class<?> paramType) {
Integer index = null;
final Class<?>[] argTypes = method.getParameterTypes();
Expand Down
@@ -1,5 +1,5 @@
/**
* Copyright 2009-2017 the original author or authors.
* Copyright 2009-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -31,6 +31,7 @@
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;

Expand Down Expand Up @@ -80,6 +81,7 @@
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.mapping.StatementType;
import org.apache.ibatis.parsing.PropertyParser;
import org.apache.ibatis.reflection.Jdk;
import org.apache.ibatis.reflection.TypeParameterResolver;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.session.Configuration;
Expand All @@ -91,6 +93,7 @@

/**
* @author Clinton Begin
* @author Kazuki Shimizu
*/
public class MapperAnnotationBuilder {

Expand Down Expand Up @@ -446,6 +449,12 @@ private Class<?> getReturnType(Method method) {
returnType = (Class<?>) ((ParameterizedType) returnTypeParameter).getRawType();
}
}
} else if (Jdk.optionalExists && Optional.class.equals(rawType)) {
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
Type returnTypeParameter = actualTypeArguments[0];
if (returnTypeParameter instanceof Class<?>) {
returnType = (Class<?>) returnTypeParameter;
}
}
}

Expand Down
16 changes: 14 additions & 2 deletions src/main/java/org/apache/ibatis/reflection/Jdk.java
@@ -1,5 +1,5 @@
/**
* Copyright 2009-2017 the original author or authors.
* Copyright 2009-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.ibatis.reflection;

import org.apache.ibatis.io.Resources;
Expand Down Expand Up @@ -52,6 +51,19 @@ public class Jdk {
dateAndTimeApiExists = available;
}

public static final boolean optionalExists;

static {
boolean available = false;
try {
Resources.classForName("java.util.Optional");
available = true;
} catch (ClassNotFoundException e) {
// ignore
}
optionalExists = available;
}

private Jdk() {
super();
}
Expand Down
33 changes: 33 additions & 0 deletions src/main/java/org/apache/ibatis/reflection/OptionalUtil.java
@@ -0,0 +1,33 @@
/**
* Copyright 2009-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.ibatis.reflection;

import java.util.Optional;

import org.apache.ibatis.lang.UsesJava8;

public abstract class OptionalUtil {

@UsesJava8
public static Object ofNullable(Object value) {
return Optional.ofNullable(value);
}

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

drop table users if exists;

create table users (
id int,
name varchar(20)
);

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

import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Optional;

public interface Mapper {

@Select("select * from users where id = #{id}")
Optional<User> getUserUsingAnnotation(Integer id);

Optional<User> getUserUsingXml(Integer id);

}
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--

Copyright 2009-2016 the original author or authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="org.apache.ibatis.submitted.usesjava8.optional_on_mapper_method.Mapper">

<select id="getUserUsingXml" resultType="org.apache.ibatis.submitted.usesjava8.optional_on_mapper_method.User">
select * from users where id = #{id}
</select>

</mapper>