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

作者站长头像
站长
· 阅读数 25

看源码的时候发现@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();
回复
1个回答
avatar
test
2024-06-20

@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);
  }
}
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容