1. 程式人生 > 其它 >MyBatis-2

MyBatis-2

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

<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對映檔案配置:

<update>:修改

<delete>:刪除

<where>:where條件

<if>:if判斷

<foreach>:迴圈

<sql>:sql片段抽取

3. MyBatis核心配置檔案深入

3.1typeHandlers標籤

無論是 MyBatis 在預處理語句(PreparedStatement)中設定一個引數時,還是從結果集中取出一個值時, 都會用型別處理器將獲取的值以合適的方式轉換成 Java 型別。下表描述了一些預設的型別處理器(擷取部分)。

你可以重寫型別處理器或建立你自己的型別處理器來處理不支援的或非標準的型別。具體做法為:實現 org.apache.ibatis.type.TypeHandler 介面, 或繼承一個很便利的類 org.apache.ibatis.type.BaseTypeHandler, 然後可以選擇性地將它對映到一個JDBC型別。例如需求:一個Java中的Date資料型別,我想將之存到資料庫的時候存成一個1970年至今的毫秒數,取出來時轉換成java的Date,即java的Date與資料庫的varchar毫秒值之間轉換。

開發步驟:

①定義轉換類繼承類BaseTypeHandler<T>

②覆蓋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="com.itheima.typeHandlers.MyDateTypeHandler"></typeHandler>
</typeHandlers>

測試新增操作:

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

資料庫資料:

測試查詢操作:

3.2 plugins標籤

MyBatis可以使用第三方的外掛來對功能進行擴充套件,分頁助手PageHelper是將分頁的複雜操作進行封裝,使用簡單的方式即可獲得分頁的相關資料

開發步驟:

①匯入通用PageHelper的座標

②在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>
③測試分頁程式碼實現
@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());

3.3 知識小結

MyBatis核心配置檔案常用標籤:

1、properties標籤:該標籤可以載入外部的properties檔案

2、typeAliases標籤:設定類型別名

3、environments標籤:資料來源環境配置標籤

4、typeHandlers標籤:配置自定義型別處理器

5、plugins標籤:配置MyBatis的外掛