Mybatis学习第22节 -- 高级结果映射 构造方法映射

知识储备:  对于大部分编程语言的函数来说, 函数的signature是函数名和函数参数,而对于函数参数的名称, 编译器不关心.   为ShopCustom创建一个构造函数
public ShopCustom(Integer id, String shopName, String shopDesc) {
this.id = id;
this.shopName = shopName;
this.shopDesc = shopDesc;
}
为ShopMapperCustom添加一个新方法
public interface ShopMapperCustom {

ShopCustom getShopById(Integer id);
ShopCustom getShopByIdConstructor(Integer id);
}
在映射文件中编写相应的配置 对于constructor的参数来说, 关心的只是要把什么内容按序填入就好了, 通过javaType来与构造函数的参数列表产生对应
<resultMap id="shopResultMapConstructor" type="ShopCustom">
<constructor>
<idArg column="shop_id" javaType="int"/>
<arg column="shop_name" javaType="string"/>
<arg column="shop_desc" javaType="string"/>
</constructor>
</resultMap>
<select id="getShopByIdConstructor" parameterType="int" resultMap="shopResultMapConstructor" >
select `shop_id`, `shop_name`, `shop_desc`
from tb_shop
where `shop_id` = #{id}
</select>
测试
@Test
public void testGetShopByIdCustomConstructor() {
SqlSession session = MyBatisUtil.getSqlSession();
ShopMapperCustom mapper = session.getMapper(ShopMapperCustom.class);
System.out.println(mapper.getShopByIdConstructor(29));
session.close();
}
结果
2018-12-29 11:53:04,097 [main] DEBUG [io.github.coinsjack.dao.ShopMapperCustom] - Cache Hit Ratio [io.github.coinsjack.dao.ShopMapperCustom]: 0.0
2018-12-29 11:53:04,484 [main] DEBUG [io.github.coinsjack.dao.ShopMapperCustom.getShopByIdConstructor] - ==> Preparing: select `shop_id`, `shop_name`, `shop_desc` from tb_shop where `shop_id` = ? 
2018-12-29 11:53:04,576 [main] DEBUG [io.github.coinsjack.dao.ShopMapperCustom.getShopByIdConstructor] - ==> Parameters: 29(Integer)
2018-12-29 11:53:04,649 [main] DEBUG [io.github.coinsjack.dao.ShopMapperCustom.getShopByIdConstructor] - <== Total: 1
ShopCustom{shopName='暴漫奶茶店', shopDesc='过来喝喝就知道啦,你是我的奶茶'}
上一篇:微服务nacos简单部署+网关设置+日志管理


下一篇:实训1:MySQL主从复制,主主复制,备份相关。