Skip to content

Commit

Permalink
Merge pull request mybatis#799 from kazuki43zoo/support-optional-mapp…
Browse files Browse the repository at this point in the history
…er-method

Support java.util.Optional as return type of mapper method
  • Loading branch information
harawata committed Mar 16, 2018
2 parents 4503f54 + 74c9ca6 commit 440f5f6
Show file tree
Hide file tree
Showing 10 changed files with 381 additions and 9 deletions.
30 changes: 24 additions & 6 deletions src/main/java/org/apache/ibatis/binding/MapperMethod.java
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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();
}
}
Original file line number Diff line number Diff line change
@@ -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');
Original file line number Diff line number Diff line change
@@ -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);

}
Original file line number Diff line number Diff line change
@@ -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>
Loading

0 comments on commit 440f5f6

Please sign in to comment.