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>//相當于where 1 = 1
<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
<!--當集合array不為空時,就繼續拼接sql語句.以 open裡面的開頭,以close裡面的結尾.item指代每一項-->
<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>
where id=#{id}
</where>
</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映射檔案配置:
“”:查詢
:插入
:修改
:删除
:where條件
:if判斷
:循環
: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
②覆寫4個未實作的方法,其中setNonNullParameter為java程式設定資料到資料庫的回調方法,getNullableResult為查詢時 mysql的字元串類型轉換成 java的Type類型的方法
③在MyBatis核心配置檔案中進行注冊
測試轉換是否正确
public class DateTypeHandler extends BaseTypeHandler<Date> {
// 将java類型轉換成資料庫需要的類型
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
long time = date.getTime();
preparedStatement.setLong(i,time);
}
//将資料庫中的類型轉換成java類型
/**
*
* @param resultSet 查詢出來的結果集
* @param s 參數
* @return
* @throws SQLException
*/
@Override
public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
long aLong = resultSet.getLong(s);
Date date = new Date(aLong);
return date;
}
//将資料庫中的類型轉換成java類型
@Override
public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
long aLong = resultSet.getLong(i);
Date date = new Date(aLong);
return date;
}
//将資料庫中的類型轉換成java類型
@Override
public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
long aLong = callableStatement.getLong(i);
Date date = new Date(aLong);
return date;
}
}
<!--注冊類型自定義轉換器-->
<typeHandlers>
<typeHandler handler="com.rg.handler.DateTypeHandler"/>
</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(){
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//設定分頁相關參數 目前也+每頁顯示的條數
PageHelper.startPage(1,3);
List <User> userList = mapper.findAll();
System.out.println(userList);
}
獲得分頁相關的其他參數
//獲得分頁相關參數
PageInfo <User> pageInfo = new PageInfo <>(userList);
System.out.println("目前頁:"+pageInfo.getPageNum());
System.out.println("每頁顯示條數"+pageInfo.getPages());
System.out.println("總條數:"+ pageInfo.getTotal());
System.out.println("總頁數:" + pageInfo.getPages());
System.out.println("上一頁:" + pageInfo.getPrePage());
System.out.println("下一頁:" + pageInfo.getNextPage());
System.out.println("是否是第一頁:" + pageInfo.isIsFirstPage());
System.out.println("是否是最後一頁:" + pageInfo.isIsLastPage());
3.3 知識小結
MyBatis核心配置檔案常用标簽:
1、properties标簽:該标簽可以加載外部的properties檔案
2、typeAliases标簽:設定類型别名
3、environments标簽:資料源環境配置标簽