1. 程式人生 > >Mybatis學習第1節 -- 列名和屬性名不一致的情況

Mybatis學習第1節 -- 列名和屬性名不一致的情況

min 語句 添加 ddr pac mapper p標簽 temp esc

第一種解決方案 別名, 在 sql語句中添加as關鍵字設置列別名

利用sqlyog數據庫管理工具的語句對表粘貼sql語句功能

對數據表點擊右鍵->粘貼sql語句-> 技術分享圖片
`book``ay_user`SELECT * FROM board LIMIT 1;`articles``admin``tb_person_info``tb_person_info`
SELECT
`shop_id`,
`owner_id`,
`area_id`,
`shop_category_id`,
`shop_name`,
`shop_desc`,
`shop_addr`,
`phone`,
`shop_img`,
`priority`,
`create_time`,
`last_edit_time`,
`enable_status`,
`advice`
FROM
`oto`.`tb_shop`
LIMIT 0, 1000 ;
在配置文件中使用上面的內容,而不需要自己重新手寫
<select id="getShopByIdAlias" parameterType="int" resultType="Shop" >
SELECT
`shop_id` as `id`,
`owner_id` as `ownerId`,
`area_id` as `areaId`,
`shop_category_id` as `categoryId`,
`shop_name` as `name`,
`shop_desc` as `desc`,
`shop_addr` as `addr`,
`phone`,
`shop_img` as `image`,
`priority` ,
`create_time` as `createTime`,
`last_edit_time` as `lastEditTime`,
`enable_status` as `enableStatus`,
`advice`
from tb_shop where `shop_id` = #{id}
</select>

第二種解決方案就是使用resultMap標簽,

type是resultMap標簽的返回類型
<resultMap id="simpleResultMap" type="Shop">
<id column="shop_id" property="id" ></id>
<result column="owner_id" property="ownerId" ></result>
<result column="area_id" property="areaId" ></result>
<result column="shop_category_id" property="categoryId" ></result>
<result column="shop_name" property="name"></result>
<result column="shop_desc" property="desc"></result>
<result column="shop_addr" property="addr"></result>
<result column="phone" property="phone"></result>
<result column="shop_img" property="image"></result>
<result column="priority" property="priority"></result>
<result column="create_time" property="createTime"></result>
<result column="last_edit_time" property="lastEditTime"></result>
<result column="enable_status" property="enableStatus"></result>
</resultMap>

分別編寫接口

public interface ShopMapper {

Shop getShopById(Integer id);
Shop getShopByIdAlias(Integer id);
}

測試使用

public class ShopMapperTest {

@Test
public void testGetShopById() {
SqlSession session = MyBatisUtil.getSqlSession();
ShopMapper mapper = session.getMapper(ShopMapper.class);
System.out.println(mapper.getShopById(1));
session.close();
}
@Test
public void testGetShopByIdAlias() {
SqlSession session = MyBatisUtil.getSqlSession();
ShopMapper mapper = session.getMapper(ShopMapper.class);
System.out.println(mapper.getShopByIdAlias(1));
session.close();
}
}

Mybatis學習第1節 -- 列名和屬性名不一致的情況