Mapper代理開發(fā)概述
之前我們寫的代碼是基本使用方式,它也存在硬編碼的問題,如下:
這里調(diào)用 selectList() 方法傳遞的參數(shù)是映射配置文件中的 namespace.id值。這樣寫也不便于后期的維護。如果使用 Mapper 代理方式(如下圖)則不存在硬編碼問題。
通過上面的描述可以看出 Mapper 代理方式的目的:
● 解決原生方式中的硬編碼
● 簡化后期執(zhí)行SQL
Mybatis 官網(wǎng)也是推薦使用 Mapper 代理的方式。下圖是截止官網(wǎng)的圖片
使用Mapper代理要求
使用Mapper代理方式,必須滿足以下要求:
● 定義與SQL映射文件同名的Mapper接口,并且將Mapper接口和SQL映射文件放置在同一目錄下。如下圖:
案例代碼實現(xiàn)
public interface UserMapper {
List<User> selectAll();
User selectById(int id);
}
● 在 com.ruanjian.mapper 包下創(chuàng)建 UserMapper接口,代碼如下:
在 resources 下創(chuàng)建 com/ruanjian/mapper 目錄,并在該目錄下創(chuàng)建 UserMapper.xml 映射配置文件
<!--
namespace:名稱空間。必須是對應(yīng)接口的全限定名
-->
<mapper namespace="com.ruanjian.mapper.UserMapper">
<select id="selectAll" resultType="com.ruanjian.pojo.User">
select *
from tb_user;
</select>
</mapper>
設(shè)置SQL映射文件的namespace屬性為Mapper接口全限定名
創(chuàng)建測試類
在 com.ruanjian 包下創(chuàng)建 MybatisDemo2 測試類,代碼如下:
/**
* Mybatis 代理開發(fā)
*/
public class MyBatisDemo2 {
public static void main(String[] args) throws IOException {
//1. 加載mybatis的核心配置文件,獲取 SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2. 獲取SqlSession對象,用它來執(zhí)行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
//3. 執(zhí)行sql
//3.1 獲取UserMapper接口的代理對象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> users = userMapper.selectAll();
System.out.println(users);
//4. 釋放資源
sqlSession.close();
}
}
注意:
如果Mapper接口名稱和SQL映射文件名稱相同,并在同一目錄下,則可以使用包掃描的方式簡化SQL映射文件的加載。也就是將核心配置文件的加載映射配置文件的配置修改為
<mappers>
<!--加載sql映射文件-->
<!-- <mapper resource="com/ruanjian/mapper/UserMapper.xml"/>-->
<!--Mapper代理方式-->
<package name="com.ruanjian.mapper"/>
</mappers>
類型別名
在映射配置文件中的 resultType 屬性需要配置數(shù)據(jù)封裝的類型(類的全限定名)。而每次這樣寫是特別麻煩的,Mybatis 提供了 類型別名(typeAliases) 可以簡化這部分的書寫。
首先需要現(xiàn)在核心配置文件中配置類型別名,也就意味著給pojo包下所有的類起了別名(別名就是類名),不區(qū)分大小寫。內(nèi)容如下:
<typeAliases>
<!--name屬性的值是實體類所在包-->
<package name="com.ruanjian.pojo"/>
</typeAliases>
通過上述的配置,我們就可以簡化映射配置文件中 resultType 屬性值的編寫
<mapper namespace="com.ruanjian.mapper.UserMapper">
<select id="selectAll" resultType="user">
select * from tb_user;
</select>
</mapper>
運行結(jié)果:
若朋友剛開始學習,這里博主整理了已經(jīng)做好的,可直接導入Maven項目,幫助你分析問題哦!文章來源:http://www.zghlxwxcb.cn/news/detail-448602.html
藍奏云網(wǎng)盤-導入此項目文章來源地址http://www.zghlxwxcb.cn/news/detail-448602.html
到了這里,關(guān)于IDEA開發(fā)實現(xiàn)Maven+Servlet+Mybatis實現(xiàn)CRUD管理系統(tǒng)-Mapper代理開發(fā)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!