mybatis手动封装查询结果

一、有些时候,我们类的属性名并不能与数据库中的列名一一对应,这时候可以使用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属性中,显然这个与我们期待的结果不同)
测试结果1

三、使用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>

测试结果,与预期的相同
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值