Mybatis的注解@ResultType的场景是什么?-灵析社区

577739990

看源码的时候发现@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();

阅读量:171

点赞量:0

问AI
"@ResultType" 注解是搭配 "ResultHandler" 来用的。 «REF: "https://mybatis.org/mybatis-3/java-api.html#mapper-> annotations" (https://link.segmentfault.com/?enc=6L2as3ciyY7OiMOygNlqpQ%3D%3D.a5XBDyN66%2FH8dPNVUw1pJEoL3LuFqlKZiqgL31ecgchUkk21tcgo8FHmGmnfU%2F4iWYvO87J8P%2FLW3hrSUOx2ow%3D%3D)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 "" 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 students; public StudentResultHandler() { students = new ArrayList(); } @Override public void handleResult(ResultContext context) { Student student = (Student)context.getResultObject(); students.add(student); } }