Mybatis的dao層實現原理

heima老師整理

 

 

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;
    }
}

測試傳統方式

@Test
public void testTraditionDao() throws IOException {
    UserDao userDao = new UserDaoImpl();
    List<User> all = userDao.findAll();
    System.out.println(all);
}

代理開發方式

代理開發方式介紹

採用 Mybatis 的代理開發方式實現 DAO 層的開發,這種方式是我們後面進入企業的主流。

Mapper 接口開發方法只需要程序員編寫Mapper 接口(相當於Dao 接口),由Mybatis 框架根據接口定義創建接口的動態代理對象,代理對象的方法體同上邊Dao接口實現類方法。

Mapper 接口開發需要遵循以下規範:

  1. Mapper.xml文件中的namespace與mapper接口的全限定名相同**
  2. Mapper接口方法名和Mapper.xml中定義的每個statement的id相同**
  3. Mapper接口方法的輸入參數類型和mapper.xml中定義的每個sql的parameterType的類型相同**
  4. Mapper接口方法的輸出參數類型和mapper.xml中定義的每個sql的resultType的類型相同**

編寫UserMapper接口

測試代理方式

@Test
public void testProxyDao() throws IOException {
    InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //獲得MyBatis框架生成的UserMapper接口的實現類
  UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    User user = userMapper.findById(1);
    System.out.println(user);
    sqlSession.close();
}

MyBatis映射文件深入

動態sql語句

動態sql語句概述

Mybatis 的映射文件中,前面我們的 SQL 都是比較簡單的,有些時候業務邏輯複雜時,我們的 SQL是動態變化的,此時在前面的學習中我們的 SQL 就不能滿足要求了。

參考的官方文檔,描述如下:

動態 SQL  之<if>

我們根據實體類的不同取值,使用不同的 SQL語句來進行查詢。比如在 id如果不爲空時可以根據id查詢,如果username 不同空時還要加入用戶名作爲條件。這種情況在我們的多條件組合查詢中經常會碰到。

<select id="findByCondition" parameterType="user" resultType="user">
    select * from User
    <where>
        <if test="id!=0">
            and id=#{id}
        </if>
        <if test="username!=null">
            and username=#{username}
        </if>
    </where>
</select>

當查詢條件id和username都存在時,控制檯打印的sql語句如下:

     //獲得MyBatis框架生成的UserMapper接口的實現類
  UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    User condition = new User();
    condition.setId(1);
    condition.setUsername("lucy");
    User user = userMapper.findByCondition(condition);

當查詢條件只有id存在時,控制檯打印的sql語句如下:

 //獲得MyBatis框架生成的UserMapper接口的實現類
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User condition = new User();
condition.setId(1);
User user = userMapper.findByCondition(condition);

動態 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="array" open="id in(" close=")" item="id" separator=",">
            #{id}
        </foreach>
    </where>
</select>

測試代碼片段如下:

 //獲得MyBatis框架生成的UserMapper接口的實現類
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int[] ids = new int[]{2,5};
List<User> userList = userMapper.findByIds(ids);
System.out.println(userList);

foreach標籤的屬性含義如下:

<foreach>標籤用於遍歷集合,它的屬性:

  • collection:代表要遍歷的集合元素,注意編寫時不要寫#{}
  • open:代表語句的開始部分
  • close:代表結束部分
  • item:代表遍歷集合的每個元素,生成的變量名
  • sperator:代表分隔符

片段抽取

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毫秒值之間轉換。

開發步驟:

  1. 定義轉換類繼承類BaseTypeHandler<T>
  2. 覆蓋4個未實現的方法,其中setNonNullParameter爲java程序設置數據到數據庫的回調方法,getNullableResult爲查詢時 mysql的字符串類型轉換成 java的Type類型的方法
  3. 在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);
    }
}

xml

<!--註冊類型自定義轉換器-->
<typeHandlers>
    <typeHandler handler="com.itheima.typeHandlers.MyDateTypeHandler"></typeHandler>
</typeHandlers>

測試添加操作:

user.setBirthday(new Date());
userMapper.add2(user);

數據庫數據:

測試查詢操作:

plugins標籤

MyBatis可以使用第三方的插件來對功能進行擴展,分頁助手PageHelper是將分頁的複雜操作進行封裝,使用簡單的方式即可獲得分頁的相關數據

開發步驟:

  1. 導入通用PageHelper的座標
  2. 在mybatis核心配置文件中配置PageHelper插件
  3. 測試分頁數據獲取

導入通用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>

測試分頁代碼實現

@Test
public 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());

 

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章