0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Mapper

Posted at

可以尝试使用以下代码来更改返回值类型:

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.SelectProvider;
import org.springframework.stereotype.Component;

@Mapper
public interface MyMapper {
    
    @SelectProvider(type = MyProvider.class, method = "getSelectSql")
    List<?> dynamicSelect(@Param("table") String table, @Param("fields") String fields, @Param("where") String where);

    class MyProvider {
        public static String getSelectSql(@Param("table") String table, @Param("fields") String fields, @Param("where") String where) {
            return String.format("select %s from %s where %s", fields, table, where);
        }
    }
    
    // 新增方法,用于修改返回值类型
    default void setReturnType(Method method, Class<?> returnType) throws NoSuchFieldException, IllegalAccessException {
        Type[] genericInterfaces = getClass().getGenericInterfaces();
        for (Type genericInterface : genericInterfaces) {
            if (genericInterface instanceof ParameterizedType) {
                ParameterizedType parameterizedType = (ParameterizedType) genericInterface;
                if (parameterizedType.getRawType().equals(MyMapper.class)) {
                    Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
                    Type returnTypeArgument = actualTypeArguments[0];
                    returnTypeArgument = returnType;
                    break;
                }
            }
        }
    }
}

然后,可以在 service 中调用 MyMapper.setReturnType() 方法来更改返回值类型,例如:

@Service
public class MyService {

    @Autowired
    private MyMapper myMapper;

    public void changeReturnType() throws NoSuchFieldException, IllegalAccessException {
        Method method = MyMapper.class.getMethod("dynamicSelect", String.class, String.class, String.class);
        myMapper.setReturnType(method, MyClass.class);
    }

}

changeReturnType() 方法中,我们获取了 dynamicSelect() 方法的 Method 对象,然后调用 myMapper.setReturnType() 方法来更改其返回值类型为 MyClass。注意,由于 setReturnType() 方法定义在 MyMapper 接口中,因此我们可以在 service 中直接通过 myMapper.setReturnType() 来调用。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?