1. 程式人生 > 實用技巧 >【02-MyBatis對映檔案、核心配置檔案】

【02-MyBatis對映檔案、核心配置檔案】

1.Mybatis的Dao層實現

1.1 傳統開發方式

1.1.1編寫UserDao介面

public interface UserDao {
    List<User> findAll() throws IOException;
}

1.1.2.編寫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;
    }
}

1.1.3 測試傳統方式

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

1.2 代理開發方式

1.2.1 代理開發方式介紹

採用 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的型別相同

1.2.2 編寫UserMapper介面

1.2.3測試代理方式

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

1.3 知識小結

MyBatis的Dao層實現的兩種方式:

手動對Dao進行實現:傳統開發方式

代理方式對Dao進行實現:

 **UserMapper userMapper = sqlSession.getMapper(UserMapper.class);**

2.MyBatis對映檔案深入

2.1 動態sql語句

2.1.1動態sql語句概述

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

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

2.1.2動態 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);
… … …

2.1.3 動態 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標籤的屬性含義如下:

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

•collection:代表要遍歷的集合元素,注意編寫時不要寫#{}

•open:代表語句的開始部分

•close:代表結束部分

•item:代表遍歷集合的每個元素,生成的變數名

•sperator:代表分隔符

2.2 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>

2.3 知識小結

MyBatis對映檔案配置: