Mybatis的Dao層實(shí)現(xiàn)原理分析
1.Mybatis的Dao層實(shí)現(xiàn)
1.1 傳統(tǒng)開發(fā)方式
1.1.1編寫UserDao接口
public interface UserDao { List<User> findAll() throws IOException; }
1.1.2.編寫UserDaoImpl實(shí)現(xiàn)
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 測試傳統(tǒng)方式
public class ServiceDemo { public static void main(String[] args) throws IOException { //創(chuàng)建dao層對象,手動編寫的 UserDao userDao=new UserDaoImpl(); List<User> all=userDao.findAll(); System.out.println(all); } }
1.2 代理開發(fā)方式
1.2.1 代理開發(fā)方式介紹
采用 Mybatis 的代理開發(fā)方式實(shí)現(xiàn) DAO 層的開發(fā),這種方式是我們后面進(jìn)入企業(yè)的主流。
Mapper 接口開發(fā)方法只需要程序員編寫Mapper 接口(相當(dāng)于Dao 接口),由Mybatis 框架根據(jù)接口定義創(chuàng)建接口的動態(tài)代理對象,代理對象的方法體同上邊Dao接口實(shí)現(xiàn)類方法。
Mapper 接口開發(fā)需要遵循以下規(guī)范:
- 1) Mapper.xml文件中的namespace與mapper接口的全限定名相同
- 2) Mapper接口方法名和Mapper.xml中定義的每個statement的id相同
- 3) Mapper接口方法的輸入?yún)?shù)類型和mapper.xml中定義的每個sql的parameterType的類型相同
- 4) Mapper接口方法的輸出參數(shù)類型和mapper.xml中定義的每個sql的resultType的類型相同
1.2.2 編寫UserMapper接口
1.2.3測試代理方式
<!--根據(jù)id進(jìn)行查詢--> <select id="findById" parameterType="int" resultType="user"> select * from user where id=#{id} </select>
public interface UserMapper { public List<User> findAll() throws IOException; public User findById(int id); }
@Test public void testProxyDao() throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = sqlSessionFactory.openSession(); //獲得MyBatis框架生成的UserMapper接口的實(shí)現(xiàn)類 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.findById(1); System.out.println(user); sqlSession.close(); }
主要是對配置文件進(jìn)行修改
1.3 知識小結(jié)
MyBatis的Dao層實(shí)現(xiàn)的兩種方式:
- 手動對Dao進(jìn)行實(shí)現(xiàn):傳統(tǒng)開發(fā)方式
- 代理方式對Dao進(jìn)行實(shí)現(xiàn): 主要用的就是這種方法
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
2.MyBatis映射文件深入
2.1 動態(tài)sql語句
2.1.1動態(tài)sql語句概述
Mybatis 的映射文件中,前面我們的 SQL 都是比較簡單的,有些時候業(yè)務(wù)邏輯復(fù)雜時,我們的 SQL是動態(tài)變化的,此時在前面的學(xué)習(xí)中我們的 SQL 就不能滿足要求了。
參考的官方文檔,描述如下:
2.1.2動態(tài) SQL 之<if>
我們根據(jù)實(shí)體類的不同取值,使用不同的 SQL語句來進(jìn)行查詢。比如在 id如果不為空時可以根據(jù)id查詢,如果username 不同空時還要加入用戶名作為條件。這種情況在我們的多條件組合查詢中經(jīng)常會碰到。
<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>
package com.itheima.mapper; import com.itheima.domain.User; import java.util.List; public interface UserMapper { public List<User> findByCondition(User user); public List<User> findByIds(List<Integer> ids); }
當(dāng)查詢條件id和username都存在時,控制臺打印的sql語句如下:
… … … //獲得MyBatis框架生成的UserMapper接口的實(shí)現(xiàn)類 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User condition = new User(); condition.setId(1); condition.setUsername("lucy"); User user = userMapper.findByCondition(condition); … … …
當(dāng)查詢條件只有id存在時,控制臺打印的sql語句如下:
… … … //獲得MyBatis框架生成的UserMapper接口的實(shí)現(xiàn)類 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User condition = new User(); condition.setId(1); User user = userMapper.findByCondition(condition); … … …
2.1.3 動態(tài) SQL 之<foreach>
循環(huán)執(zhí)行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接口的實(shí)現(xiàn)類 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); int[] ids = new int[]{2,5}; List<User> userList = userMapper.findByIds(ids); System.out.println(userList); … … …
foreach標(biāo)簽的屬性含義如下:
<foreach>標(biāo)簽用于遍歷集合,它的屬性:
collection
:代表要遍歷的集合元素,注意編寫時不要寫#{}open
:代表語句的開始部分close
:代表結(jié)束部分item
:代表遍歷集合的每個元素,生成的變量名sperator
:代表分隔符
2.2 SQL片段抽取
Sql 中可將重復(fù)的 sql 提取出來,使用時用 include 引用即可,最終達(dá)到 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 知識小結(jié)
- <
select
>:查詢 - <
insert
>:插入 - <
update
>:修改 - <
delete
>:刪除 - <
where
>:where條件 - <
if
>:if判斷 - <
foreach
>:循環(huán) - <
sql
>:sql片段抽取
3. MyBatis核心配置文件深入
3.1typeHandlers標(biāo)簽
無論是 MyBatis 在預(yù)處理語句(PreparedStatement)中設(shè)置一個參數(shù)時,還是從結(jié)果集中取出一個值時, 都會用類型處理器將獲取的值以合適的方式轉(zhuǎn)換成 Java 類型。
下表描述了一些默認(rèn)的類型處理器(截取部分)。
你可以重寫類型處理器或創(chuàng)建你自己的類型處理器來處理不支持的或非標(biāo)準(zhǔn)的類型。
具體做法為:實(shí)現(xiàn) org.apache.ibatis.type.TypeHandler 接口, 或繼承一個很便利的org.apache.ibatis.type.BaseTypeHandler, 然后可以選擇性地將它映射到一個JDBC類型。例如需求:一個Java中的Date數(shù)據(jù)類型,我想將之存到數(shù)據(jù)庫的時候存成一個1970年至今的毫秒數(shù),取出來時轉(zhuǎn)換成java的Date,即java的Date與數(shù)據(jù)庫的varchar毫秒值之間轉(zhuǎn)換。
開發(fā)步驟:
①定義轉(zhuǎn)換類繼承類BaseTypeHandler<T>
②覆蓋4個未實(shí)現(xiàn)的方法,其中setNonNullParameter為java程序設(shè)置數(shù)據(jù)到數(shù)據(jù)庫的回調(diào)方法,getNullableResult為查詢時 mysql的字符串類型轉(zhuǎn)換成 java的Type類型的方法
③在MyBatis核心配置文件中進(jìn)行注冊
測試轉(zhuǎn)換是否正確
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.itheima.mapper.UserMapper"> <insert id="save" parameterType="user"> insert into user values(#{id},#{username},#{password},#{birthday}) </insert> <select id="findById" parameterType="int" resultType="user"> select * from user where id=#{id} </select> <select id="findAll" resultType="user"> select * from user </select> </mapper>
package com.itheima.handler; import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; public class DateTypeHandler extends BaseTypeHandler<Date> { //將java類型 轉(zhuǎn)換成 數(shù)據(jù)庫需要的類型i是參數(shù)位置 public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException { long time = date.getTime(); preparedStatement.setLong(i,time); } //將數(shù)據(jù)庫中類型 轉(zhuǎn)換成java類型 //String參數(shù) 要轉(zhuǎn)換的字段名稱 //ResultSet 查詢出的結(jié)果集 public Date getNullableResult(ResultSet resultSet, String s) throws SQLException { //獲得結(jié)果集中需要的數(shù)據(jù)(long) 轉(zhuǎn)換成Date類型 返回 long aLong = resultSet.getLong(s); Date date = new Date(aLong); return date; } //將數(shù)據(jù)庫中類型 轉(zhuǎn)換成java類型 public Date getNullableResult(ResultSet resultSet, int i) throws SQLException { long aLong = resultSet.getLong(i); Date date = new Date(aLong); return date; } //將數(shù)據(jù)庫中類型 轉(zhuǎn)換成java類型 public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException { long aLong = callableStatement.getLong(i); Date date = new Date(aLong); return date; } }
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); } }
<!--注冊類型自定義轉(zhuǎn)換器--> <typeHandlers> <typeHandler handler="com.itheima.typeHandlers.MyDateTypeHandler"></typeHandler> </typeHandlers>
測試添加操作:
數(shù)據(jù)庫數(shù)據(jù):
測試查詢操作:
3.2 plugins標(biāo)簽
MyBatis可以使用第三方的插件來對功能進(jìn)行擴(kuò)展,分頁助手PageHelper是將分頁的復(fù)雜操作進(jìn)行封裝,使用簡單的方式即可獲得分頁的相關(guān)數(shù)據(jù)
開發(fā)步驟:
①導(dǎo)入通用PageHelper的坐標(biāo)
②在mybatis核心配置文件中配置PageHelper插件
③測試分頁數(shù)據(jù)獲取
①導(dǎo)入通用PageHelper坐標(biāo)
<!-- 分頁助手 --> <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>
③測試分頁代碼實(shí)現(xiàn)
@Test public void testPageHelper(){ //設(shè)置分頁參數(shù) PageHelper.startPage(1,2); List<User> select = mapper.findAll(); for(User user : userList){ System.out.println(user); } }
獲得分頁相關(guān)的其他參數(shù)
//其他分頁的數(shù)據(jù) PageInfo<User> pageInfo = new PageInfo<User>(select); System.out.println("總條數(shù):"+pageInfo.getTotal()); System.out.println("總頁數(shù):"+pageInfo.getPages()); System.out.println("當(dāng)前頁:"+pageInfo.getPageNum()); System.out.println("每頁顯示長度:"+pageInfo.getPageSize()); System.out.println("是否第一頁:"+pageInfo.isIsFirstPage()); System.out.println("是否最后一頁:"+pageInfo.isIsLastPage());
3.3 知識小結(jié)
MyBatis核心配置文件常用標(biāo)簽:
1、properties標(biāo)簽:該標(biāo)簽可以加載外部的properties文件
2、typeAliases標(biāo)簽:設(shè)置類型別名
3、environments標(biāo)簽:數(shù)據(jù)源環(huán)境配置標(biāo)簽
4、typeHandlers標(biāo)簽:配置自定義類型處理器
5、plugins標(biāo)簽:配置MyBatis的插件
總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java中的List接口實(shí)現(xiàn)類LinkList和ArrayList詳解
這篇文章主要介紹了Java中的List接口實(shí)現(xiàn)類LinkList和ArrayList詳解,List接口繼承自Collection接口,是單列集合的一個重要分支,實(shí)現(xiàn)了List接口的對象稱為List集合,在List集合中允許出現(xiàn)重復(fù)的元素,所有的元素是以一種線性方式進(jìn)行存儲的,需要的朋友可以參考下2024-01-01Springboot配置security basic path無效解決方案
這篇文章主要介紹了Springboot配置security basic path無效解決方案,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09教你使用springSecurity+jwt實(shí)現(xiàn)互踢功能
JWT作為一個開放的標(biāo)準(zhǔn)( RFC 7519 ),定義了一種簡潔的,自包含的方法用于通信雙方之間以Json對象的形式安全的傳遞信息。接下來通過本文給大家介紹springSecurity+jwt實(shí)現(xiàn)互踢功能,需要的朋友可以參考下2021-11-11