Mybatis注解开发之@Results
<p><strong>写在前面:</strong>在使用mybatis注解开发的时候,数据库返回的结果集和实体类字段不对应,我们就需要手动指定映射关系;</p>
一种是使用在 xml 文件中指定 resultMap,指定 id,下面需要的直接引用 id 就可以;
另一种在使用注解开发的时候,我们只能通过注解 @Results 来指定对应关系了,那么注解只能每个方法用到了都得复制一遍 @Results 吗?答案当然不是,注解 @Results 中提供了 id 属性这就跟 xml 文件中的 id 作用一样,下面引用的话可以用 @ResultMap 来引用。
首先说明一下 @Results 各个属性的含义,id 为当前结果集声明唯一标识,value 值为结果集映射关系,@Result 代表一个字段的映射关系,column 指定数据库字段的名称,property 指定实体类属性的名称,jdbcType 数据库字段类型,@Result 里的 id 值为 true 表明主键,默认 false;使用 @ResultMap 来引用映射结果集,其中 value 可省略。
声明结果集映射关系代码:
@Select({"select id, name, class_id from my_student"})
@Results(id="studentMap", value={@Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="name", property="name", jdbcType=JdbcType.VARCHAR),
@Result(column="class_id", property="classId", jdbcType=JdbcType.INTEGER)
})
List<Student> selectAll();
引用结果集代码:
@Select({"select id, name, class_id from my_student where id = #{id}"})
@ResultMap(value="studentMap")
Student selectById(integer id);
这样我们就不用每次需要声明结果集映射的时候都复制冗余代码,简化开发,提高了代码的复用性。