【SSM框架系列】Mybatis映射配置文件与核心配置文件深入
傳統開發方式Dao層實現
編寫UserDao接口
public interface UserDao {List<User> findAll() throws IOException;}編寫UserDaoImpl實現
public class UserDaoImpl implements UserDao {public List<User> findAll() throws IOException {InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();List<User> userList = sqlSession.selectList("userMapper.findAll");sqlSession.close();return userList;}}測試
@Testpublic void testTraditionDao() throws IOException {UserDao userDao = new UserDaoImpl();List<User> all = userDao.findAll();System.out.println(all);}Mybatis代理開發方式介紹
Mapper 接口開發方法只需要程序員編寫Mapper 接口(相當于Dao 接口),由Mybatis 框架根據接口定義創建接口的動態代理對象,代理對象的方法體同上邊Dao接口實現類方法。
Mapper 接口開發需要遵循以下規范:
Mapper.xml文件中的namespace與mapper接口的全限定名相同
Mapper接口方法名和Mapper.xml中定義的每個statement的id相同
Mapper接口方法的輸入參數類型和mapper.xml中定義的每個sql的parameterType的類型相同
Mapper接口方法的輸出參數類型和mapper.xml中定義的每個sql的resultType的類型相同
分析:
映射配置文件中的namespace為什么要和接口的全限定類名一樣?
- 在加載核心配置文件時,可以獲取映射配置文件,Mybatis就會去加載映射配置文件,解析里面的namespace和每個Statement,將解析到結果保存到一個Map中,Map的key是namespace + id,Map的Value是Mapper對象(SQL,結果集)
- 在使用代理對象去調用接口方法時,Mybatis可以使用反射區拿到該調用方法的名稱和當前類的全限定類名,然后將全限定類名 + 方法名稱,組成一個Key,再去Map中查詢對應的Key
- 如果有就可以找到對應的Value,而Value中就有要執行的SQL和封裝的結果集
- 所以namespace必須和接口的全限定類名一致,id必須和接口中的方法名稱一致
MyBatis映射文件深入
獲取主鍵自增id
<insert id="addUser" parameterType="user"><!--selectKey 標簽可以用來獲取新插入數據的主鍵keyProperty屬性是指實體類中主鍵的屬性名稱keyColumn屬性是指表中主鍵的字段名稱resultType屬性是指主鍵的數據類型order是指獲取主鍵的函數是在插入語句之前執行還是之后執行AFTER表示之后,用于主鍵自增長BEFORE表示之前,用于主鍵非自增長select last_insert_id():得到剛 insert 進去記錄的主鍵值,只適用與自增主鍵--><selectKey resultType="int" keyProperty="id" keyColumn="id" order="AFTER">select last_insert_id()</selectKey>INSERT into t_user VALUES (#{id},#{username},#{password})</insert>結果集Map封裝
<!--resultMap 標簽可以用來描述實體類中的屬性和表中字段的對應關系id屬性是resultMap的標志,要求在同一個映射文件中唯一type屬性是用來指定這個resultMap 要描述的實體對象是誰--><resultMap id="xxoo" type="user"><!--<id>標簽是用來描述主鍵的對應關系<result>標簽是用來描述非主鍵的對應關系property屬性是用來指定實體中的屬性名稱column屬性是用來指定表中的字段名稱--><id property="id" column="id"></id><result property="name" column="username"></result><result property="password" column="password"></result></resultMap>動態 SQL 之 - if
根據實體類的不同取值,使用不同的 SQL語句來進行查詢。比如在 id如果不為空時可以根據id查詢,如果username 不同空時還要加入用戶名作為條件。這種情況在我們的多條件組合查詢中經常會碰到。
<select id="findByCondition" parameterType="user" resultType="user">select * from User<!--where標簽可以自動處理and如果有條件滿足,會自動刪除第一個and如果都不滿足,where條件就不會出現--><where><!--test中的表達式:如果有實體類中的屬性,可以直接寫,不要加#{}或者${}而且注意大小寫,必須和實體類中的屬性名稱一致--><if test="id!=0">and id=#{id}</if><if test="username!=null">and username=#{username}</if></where></select>動態 SQL 之 - foreach
循環執行sql的拼接操作,例如:SELECT * FROM USER WHERE id IN (1,2,5)。
<select id="findByIds" parameterType="list" resultType="user">select * from User<where><!--foreach 標簽是用來遍歷的collection屬性是指定要遍歷的類型open屬性是sql語句拼接的開始close屬性是sql語句拼接的結束item屬性是遍歷的每個元素separator屬性是連接多個元素的分隔符#{item的名稱}:取值--><foreach collection="array" open="id in(" close=")" item="id" separator=",">#{id}</foreach></where></select> <update id="xxxxx" parameterType="user">update usero <set> <!--如果滿足條件,set標簽可以去除最后一個逗號--><if test="username!= null">username=#{username},</if><if test="password!= null">password=#{password},</if> <set>where id=#{id}</update>SQL片段抽取:Sql 中可將重復的 sql 提取出來,使用時用 include 標簽引用即可,最終達到 sql 重用的目的
<!--抽取sql片段簡化編寫--><sql id="selectUser" select * from User</sql><select id="findById" parameterType="int" resultType="user"><include refid="selectUser"></include> where id=#{id}</select><select id="findByIds" parameterType="list" resultType="user"><include refid="selectUser"></include><where><foreach collection="array" open="id in(" close=")" item="id" separator=",">#{id}</foreach></where></select>MyBatis核心配置文件深入
typeHandlers標簽:配置類型轉換器
無論是 MyBatis 在預處理語句(PreparedStatement)中設置一個參數時,還是從結果集中取出一個值時, 都會用類型處理器將獲取的值以合適的方式轉換成 Java 類型。下表描述了一些默認的類型處理器(截取部分)。
可以重寫類型處理器或創建你自己的類型處理器來處理不支持的或非標準的類型。具體做法為:實現 org.apache.ibatis.type.TypeHandler 接口, 或繼承一個很便利的類 org.apache.ibatis.type.BaseTypeHandler, 然后可以選擇性地將它映射到一個JDBC類型。
例如需求:一個Java中的Date數據類型,我想將之存到數據庫的時候存成一個1970年至今的毫秒數,取出來時轉換成java的Date,即java的Date與數據庫的varchar毫秒值之間轉換。
步驟:
-
定義轉換類繼承類BaseTypeHandler
-
覆蓋4個未實現的方法,其中setNonNullParameter為java程序設置數據到數據庫的回調方法,getNullableResult為查詢時 mysql的字符串類型轉換成 java的Type類型的方法
-
在MyBatis核心配置文件中進行注冊
代碼如下:
public class MyDateTypeHandler extends BaseTypeHandler<Date> {public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType type) {preparedStatement.setString(i,date.getTime()+"");}public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {return new Date(resultSet.getLong(s));}public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {return new Date(resultSet.getLong(i));}public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {return callableStatement.getDate(i);}} <!--注冊類型自定義轉換器--><typeHandlers><typeHandler handler="cs.wy.typeHandlers.MyDateTypeHandler"></typeHandler></typeHandlers>plugins標簽:Mybatis的分頁插件
MyBatis可以使用第三方的插件來對功能進行擴展,分頁助手PageHelper是將分頁的復雜操作進行封裝,使用簡單的方式即可獲得分頁的相關數據
導入通用PageHelper坐標
<!-- 分頁助手 --><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>3.7.5</version></dependency><dependency><groupId>com.github.jsqlparser</groupId><artifactId>jsqlparser</artifactId><version>0.9.1</version></dependency>在mybatis核心配置文件中配置PageHelper插件
<!-- 注意:分頁助手的插件 配置在通用館mapper之前 --><plugin interceptor="com.github.pagehelper.PageHelper"><!-- 指定方言 --><property name="dialect" value="mysql"/></plugin>分頁代碼實現
@Testpublic void testPageHelper(){//設置分頁參數// 第一個參數是開始的頁碼// 第二個參數是每頁顯示條數PageHelper.startPage(1,2);List<User> select = userMapper2.select(null);for(User user : select){System.out.println(user);}//其他分頁的數據PageInfo<User> pageInfo = new PageInfo<User>(select);System.out.println("總條數:"+pageInfo.getTotal());System.out.println("總頁數:"+pageInfo.getPages());System.out.println("當前頁:"+pageInfo.getPageNum());System.out.println("每頁顯示長度:"+pageInfo.getPageSize());System.out.println("是否第一頁:"+pageInfo.isIsFirstPage());System.out.println("是否最后一頁:"+pageInfo.isIsLastPage());}MyBatis核心配置文件常用標簽:
1、properties標簽:該標簽可以加載外部的properties文件
2、typeAliases標簽:設置類型別名
3、environments標簽:數據源環境配置標簽
4、typeHandlers標簽:配置自定義類型處理器
5、plugins標簽:配置MyBatis的插件
總結
以上是生活随笔為你收集整理的【SSM框架系列】Mybatis映射配置文件与核心配置文件深入的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【SSM框架系列】Mybatis基本介绍
- 下一篇: 【十大经典排序算法】java实现--插入