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