Mybatis的注解@ResultType的场景是什么?

看源码的时候发现@ResultType只有在返回值类型为void时才会生效。

//源码参考: org.apache.ibatis.builder.annotation.MapperAnnotationBuilder#getReturnType
if (void.class.equals(returnType)) {
  ResultType rt = method.getAnnotation(ResultType.class);
  if (rt != null) {
      returnType = rt.value();
  }
}

那么假如我的应用代码如下,请问,queryStudent如何返回Student对象?或者说@ResultType的意义是什么?

@Select("select * from Student")
@ResultType(Student.class)
void queryStudent();
阅读 592
1 个回答

@ResultType 注解是搭配 ResultHandler 来用的。

REF: https://mybatis.org/mybatis-3/java-api.html#mapper-annotations

This annotation is used when using a result handler. In that case, the return type is void so MyBatis must have a way to determine the type of object to construct for each row. If there is an XML result map, use the @ResultMap annotation. If the result type is specified in XML on the <select> element, then no other annotation is necessary. In other cases, use this annotation. For example, if a @Select annotated method will use a result handler, the return type must be void and this annotation (or @ResultMap) is required. This annotation is ignored unless the method return type is void.

所以你那个写法不对,起码你得定义一个 ResultHandler 出来:

@Select("select * from Student")
@ResultType(Student.class)
void queryStudent(StudentResultHandler resultHandler);



public class StudentResultHandler implements ResultHandler {
  private final List<Student> students;

  public StudentResultHandler() {
    students = new ArrayList<>();
  }

  @Override
  public void handleResult(ResultContext context) {
    Student student = (Student)context.getResultObject();
    students.add(student);
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏