MyBatis自定义映射resultMap
当数据库表的字段名和实体类中的属性名不一致,则可以通过resultMap设置自定义映射。下面是resultMap的演示。
准备
数据库表
t_student表
实体类对象
为了体现出resultMap的特点,所以如下类作为实体类对象。
MyBatis自定义映射resultMap
这里以通过查询一条数据进行演示(以id作为参数进行查询)。
映射接口
publicinterfaceTMapper{//通过id查询TselectStudentById(@Param("id")Integer id);}
映射文件
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--约束,约束不同xml中所写的标签也不同--><mappernamespace="com.xxx.mapper.TMapper"><!--接口--><resultMapid="ttype"type="com.xxx.pojo.T"><idproperty="a"column="id"></id><resultproperty="b"column="name"></result><resultproperty="c"column="age"></result><resultproperty="d"column="sex"></result></resultMap><!-- T selectStudentById(@Param("id")Integer id);--><selectid="selectStudentById"resultMap="ttype">
select * from t_student where id=#{id}</select></mapper>
解释
(1)select标签
select标签中写查询语句。
id:所写的是映射接口中的方法名。
resultMap:写的是resultMap标签中的id属性的值。
<selectid="selectStudentById"resultMap="ttype">
select * from t_student where id=#{id}</select>
(2)resultMap标签
resultMap标签中用于设置自定义映射。
id:表示自定义映射的唯一标识。
type:查询的数据要映射的实体类的类型。
resultMap的子标签
id:设置主键的映射关系。
result:设置普通字段的映射关系。
property:设置映射关系中实体类中的属性名。
column:设置映射关系中表中的字段名。
<resultMapid="ttype"type="com.xxx.pojo.T"><idproperty="a"column="id"></id><resultproperty="b"column="name"></result><resultproperty="c"column="age"></result><resultproperty="d"column="sex"></result></resultMap>
测试
/*省略获取MyBatis核心配置文件等*///通过代理模式创建TMapper接口的代理实现类对象TMapper mapper= sqlSession.getMapper(TMapper.class);//通过id查询T t= mapper.selectStudentById(1);//输出查询结果System.out.println(t);
输出结果