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

Posted 积水成渊

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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=‘过来喝喝就知道啦,你是我的奶茶‘}

以上是关于Mybatis学习第22节 -- 高级结果映射 构造方法映射的主要内容,如果未能解决你的问题,请参考以下文章

MyBatis学习10高级映射之多对多查询

MyBatis学习10高级映射之多对多查询

MyBatis结果映射与MyBatis缓存初探学习记录

Mybatis学习第8节 -- 动态sql-if

MyBatis学习09高级映射之一对多查询

Mybatis 高级结果映射 ResultMap Association Collection