1. 程式人生 > >Mybatis學習第22節 -- 高級結果映射 構造方法映射

Mybatis學習第22節 -- 高級結果映射 構造方法映射

hit ble deb ron ger ont 列表 idc class

知識儲備: 對於大部分編程語言的函數來說, 函數的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節 -- 高級結果映射 構造方法映射