一、有些时候,我们类的属性名并不能与数据库中的列名一一对应,这时候可以使用resultMap接收查询结果,手动封装属性与列的映射关系
二、先看没有手动封装时的查询结果(即使用resultType接收查询数据):
bean类,其中的属性名c_country与数据库列country不能完全对应
public class Country {
private Integer cid;//数据库中是cid
private String c_country;//对应数据库中的country,测试手动封装查询数据
private String capital;//对应数据库中capital
public Integer getCid() {
return cid;
}
public void setCid(Integer cid) {
this.cid = cid;
}
public String getC_country() {
return c_country;
}
public void setC_country(String c_country) {
this.c_country = c_country;
}
public String getCapital() {
return capital;
}
public void setCapital(String capital) {
this.capital = capital;
}
@Override
public String toString() {
return "Country [cid=" + cid + ", c_country=" + c_country + ", capital=" + capital + "]";
}
}
mapper接口
public interface CountryMapper {
//查询所有国家信息
public List<Country> selectAll();
}
mapper.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis_demo.mapper.CountryMapper">
<select id="selectAll" resultType="com.mybatis_demo.domain.Country" resultMap="">
select * from t_country
</select>
</mapper>
测试代码
public class TestMapType {
@Test
public void test1() {
try {
InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = builder.build(in);
SqlSession session = sqlSessionFactory.openSession();
CountryMapper mapper = session.getMapper(CountryMapper.class);
List<Country> list = mapper.selectAll();
for (Country country : list) {
System.out.println(country);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试结果(由于属性名c_country与数据库列country不能完全对应,所以无法将查询结果中的country列的值封装到country中的c_country属性中,显然这个与我们期待的结果不同)
三、使用resultMap手动封装查询结果
相比没有手动封装查询结果只需要修改mapper.xml映射文件
mapper.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis_demo.mapper.CountryMapper">
<!-- 封装查询结果,只需将不对应的属性进行手动封装 -->
<resultMap type="com.mybatis_demo.domain.Country" id="country">
<result property="c_country" column="country"/>
</resultMap>
<select id="selectAll" resultMap="country">
select * from t_country
</select>
</mapper>
测试结果,与预期的相同