柚子快報激活碼778899分享:Mybatis筆記
柚子快報激活碼778899分享:Mybatis筆記
1.Mybatis簡介
1.1MyBatis特性
MyBatis是支持定制化SQL、存儲過程以及高級映射的優(yōu)秀的持久層框架
MyBatsi避免了幾乎所有的JDBC代碼和手動設(shè)置參數(shù)以及獲取結(jié)果集
MyBatis可以使用簡單的XML或注解用于配置和原始映射,將接口和Java的POJO(Plain Old Java Objects,普通的Java對象)映射成數(shù)據(jù)庫中的記錄
MyBatis是一個半自動的ORM(Object Relation Mapping)框架
1.2持久層技術(shù)對比
1.2.1JDBC
SQL夾雜在Java代碼中耦合度高,導(dǎo)致硬編碼內(nèi)傷
維護不易且實際開發(fā)需求中SQL有變化,頻繁修改的情況多見
代碼冗長,開發(fā)效率低
1.2.2Hibernate
操作簡單,開發(fā)效率高
程序中的長難復(fù)雜SQL需要繞過框架
內(nèi)部自動生產(chǎn)的SQL,不容易做特殊優(yōu)化
基于全映射的全自動框架,大量字段的POJO進行部分映射時比較困難
反射操作太多,導(dǎo)致數(shù)據(jù)庫性能下降
1.2.3MyBatis
輕量級,性能出色
SQL和Java編碼分開,功能邊界清晰,Java代碼專注業(yè)務(wù)、SQL語句專注數(shù)據(jù)
開發(fā)效率稍遜于Hibernate,但是完全能夠接受
2.MyBatis框架搭建及簡單測試
ORM:Object Relationship Mapping,對象關(guān)系映射。
對象:Java的實體類的對象關(guān)系:關(guān)系型數(shù)據(jù)庫映射:二者之間的對應(yīng)關(guān)系
Java概念數(shù)據(jù)庫概念類表屬性字段/列對象2.1MyBatis配置文件記錄/行
2.1MyBatis配置文件
resources下新建mybatis-config.xml文件,寫入配置
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
2.2MyBatis映射文件創(chuàng)建 2.2.1映射文件的命名規(guī)則 表所對應(yīng)的實體類的類名+Mapper.xml,如:UserMapper.xml 因此一個映射文件對應(yīng)一個實體類,對應(yīng)一張表的操作 MyBatis映射文件用于編寫SQL,訪問以及操作表中的數(shù)據(jù) MyBatis映射文件存放的位置是src/main/resources/mappers目錄下 2.2.2MyBatis面向接口編程的一致性 【表----實體類----mapper接口----映射文件】 MyBatis面向接口編程的兩個一致: 映射文件的namespace要和mapper接口的全類名保持一致映射文件中SQL語句的id要和mapper接口中的方法名一致 Mapper.xml中: PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> Mapper接口中: public interface UserMapper{ //添加用戶信息 int insertUser(); } Mapper.xml中: insert into t_user values(null,'admin','123456',23,'男','123456@qq.com') 2.3MyBatis簡單測試-添加功能 通過sqlSession.getMapper(XXXMapepr.class)方法來獲取mapper接口 調(diào)用mapper接口執(zhí)行完SQL后需要手動提交事務(wù) @Test public void test() throws IOException{ //加載核心配置文件 InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); //獲取SqlSessionFactoryBuilder SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); //獲取SqlSessionFactory SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is); //獲取SqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); //獲取mapper接口對象 UserMapper mapper = sqlSession.getMapper(UserMapper.class); //測試功能 int result = mapper.insertUser(); //手動提交事務(wù),不提交事務(wù)的話沒效果 sqlSession.commit(); sout("result: "+result); } 2.4功能優(yōu)化 2.4.1自動提交事務(wù) 上述實現(xiàn),在每一次SQL執(zhí)行后都需要手動提交事務(wù),sqlSession默認不自動提交事務(wù) 若需要自動提交事務(wù),可以使用sqlSessionFactory.openSession(true)方法,把參數(shù)設(shè)置成true,默認是false,true表示自動提交 @Test public void test() throws IOException{ //加載核心配置文件 InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); //獲取SqlSessionFactoryBuilder SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); //獲取SqlSessionFactory SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is); //獲取SqlSession,參數(shù)設(shè)置為true為自動提交,默認是false SqlSession sqlSession = sqlSessionFactory.openSession(true); //獲取mapper接口對象 UserMapper mapper = sqlSession.getMapper(UserMapper.class); //測試功能 int result = mapper.insertUser(); sout("result: "+result); } 2.4.2加入log4j日志功能 在SQL執(zhí)行過程中希望在控制臺打印出執(zhí)行過程,可加入log4j日志功能 1.加入依賴: 2.加入log4j的配置文件: log4j的配置文件名為log4j.xml,存放的位置是src/main/resources目錄下 日志的級別: FATAL(致命)>ERROR(錯誤)>WARN(警告)>INFO(信息)>DEBUG(調(diào)試) 從左到右打印的內(nèi)容越來越詳細 2.5MyBatis其他功能測試 2.5.1修改功能 從接口開始寫,先在mapper接口里面定義方法,再寫.xml中的實現(xiàn)SQL void updateUser(); update t_user set username = "張三" where id = 4 @Test public void testUpdate() throws IOException{ InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(true); UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.updateUser();//無返回值 } 2.5.2刪除功能 void delUser(); delete from t_user where id = 4 @Test public void testDel() throws IOException{ InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(true); UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.delUser();//無返回值 } 2.5.3查詢功能 查詢是有返回值的,在寫之前要設(shè)置好 注意: 查詢功能的標簽必須設(shè)置resultType或resultMap,不然無法找到返回值類型進行映射resultType:設(shè)置默認的映射關(guān)系resultMap:設(shè)置自定義的映射關(guān)系 2.5.3.1查詢單個信息 //根據(jù)id返回查詢用戶信息 User getUserById(); select * from t_user where id = 3 @Test public void test() throws IOException{ InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(true); UserMapper mapper = sqlSession.getMapper(UserMapper.class); //測試,返回一個User對象 User user = mapper.getUserById; sout(user); } 2.5.3.2查詢集合信息 //查詢所有的用戶信息 List select * from t_user @Test public void test() throws IOException{ InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(true); UserMapper mapper = sqlSession.getMapper(UserMapper.class); //測試,返回一個User對象 List userList.forEach(user -> sout(user)); } 3.核心配置文件 3.1environment詳解 environments:配置多個連接數(shù)據(jù)庫的環(huán)境 屬性: default:設(shè)置默認使用的環(huán)境id environment:配置某個連接數(shù)據(jù)庫的具體環(huán)境 屬性: idL:表示連接數(shù)據(jù)庫環(huán)境的唯一標識,不能重復(fù) transactionManager:設(shè)置事務(wù)管理方式 屬性: ? type=”JDBC|MANAGED“ ? JDBC:表示當(dāng)前環(huán)境中,執(zhí)行SQL時,使用的是JDBC中原生的事務(wù)管理方式,事務(wù)的提交或回滾需要手動處理 ? MANAGED:被管理,例如Spring dataSource:配置數(shù)據(jù)源 屬性: ? type:設(shè)置數(shù)據(jù)源的類型 ? type=”POOLED|UNPOOLED|JNDI“ ? POOLED:表示使用數(shù)據(jù)庫連接池緩存數(shù)據(jù)庫連接 ? UNPOOLED:表示不使用數(shù)據(jù)庫連接池 ? JNDI:表示使用上下文中的數(shù)據(jù)源 3.2properties詳解 可以創(chuàng)建jdbc.properties文件來單獨存放數(shù)據(jù)庫配置信息 jdbc.properties文件中: jdbc.driver = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3306/XXX jdbc.username = root jdbc.password = 123456 mybatis-config.xml文件中: PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> 3.3typeAliases詳解 如下,在resultType里面需要每一次都寫實體類路徑全稱,比較麻煩 select * from t_user MyBatis提供了類型別名的功能:typeAliases標簽,設(shè)置默認/指定的類型別名。寫了alias屬性代表指定用"User"直接代替"com…pojo.user",如果不寫則默認使用實體類名代替,且不區(qū)分大小寫 typeAliases:設(shè)置類型別名 typeAlias:設(shè)置某個類型的別名 屬性: ? type:設(shè)置需要設(shè)置別名的類型 ? alias:設(shè)置某個類型的別名。如設(shè)置,則是指定值;如不設(shè)置,則默認使用實體類的類名,不區(qū)分大小寫 package:以包為單位,將包下所有的類型設(shè)置默認的類型別名,即類名且不區(qū)分大小寫 注意:MyBatis核心配置文件中,標簽需要按照順序去配置,順序如下: properties?----settings?----typeAliases?----typeHandlers?----objectFactory?----objectWrapperFactory?----reflectorFactory?----plugins?----environments?----databaseIdProvider?----mappers? PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!--name里面填入.xml文件放置的包名--> 上述類型別名設(shè)置后,.xml中的resultType值可以直接使用實體類名,且不區(qū)分大小寫 select * from t_user 3.4mappers詳解 上述映射文件的引入,都是單個引入,后續(xù).xml文件增多后不太方便 MyBatis提供以包為單位進行映射文件的引入 package:以包為單位引入映射文件 要求:不然無法綁定識別 mapper接口所在的包要和映射文件所在的包一致mapper接口要和映射文件的名字一致 <!--name里面填入.xml文件放置的包名--> 注意:resources底下創(chuàng)建包時沒有package,只能創(chuàng)建directory,創(chuàng)建的時候名字不能直接用“com.atguigu.mybatis.mapper”,這種創(chuàng)建出來的只是一個文件夾,沒有目錄結(jié)構(gòu),需要使用“com/atguigu/mybatis/mapper”去創(chuàng)建,這樣才是一個有目錄層級的包,創(chuàng)建完成后也會轉(zhuǎn)換成“.”的格式 4.IDEA中使用MyBatis 4.1IDEA中模板設(shè)置 打開File–Settings–Editor–File and Code Template 然后添加mybatis-config模板,將內(nèi)容復(fù)制到這里面,模板名Name為mybatis-config,后綴Extension為xml 這樣的話在新項目中配置mybatis就可以直接創(chuàng)建模板文件,只需要在里面修改內(nèi)容即可 其他模板創(chuàng)建也類似,如創(chuàng)建mybatis-mapper.xml模板: PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 4.2封裝SqlSessionUtils工具類 獲取sqlSession對象的過程是重復(fù)的,我們可以把它單獨擰出來封裝在utils工具類中 創(chuàng)建一個utils包,新建SqlSessionUtils類,在里面寫獲取SqlSession對象的代碼 public class SqlSessionUtils { public static SqlSession getSqlSession() { SqlSession sqlSession = null; try { //加載核心配置文件 InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); //獲取SqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //獲取SqlSession SqlSession sqlSession = sqlSessionFactory.openSession(true); } catch(IOException e) { e.printStackTrace(); } return sqlSession; } } 測試使用: @Test public void test(){ //直接調(diào)用SqlSessionUtils工具類獲取sqlSession對象 SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List userList.forEach(user -> sout(user)); } 5.MyBatis獲取參數(shù)值情況 MyBatis獲取參數(shù)值的兩種方式:${}和#{} ${}:本質(zhì)字符串拼接,要注意單引號‘ ’問題#{}:本質(zhì)占位符賦值,更推薦使用以上兩種可根據(jù)實際場景選用 MyBatis獲取參數(shù)值的各種情況: 5.1mapper接口方法的參數(shù)為單個 可以通過KaTeX parse error: Expected 'EOF', got '#' at position 4: {}和#?{}以任意的名稱獲取參數(shù)值,但…{}的單引號問題。具體使用如下: mapper接口中: //根據(jù)用戶名查詢用戶 User getUserByUsername(String username); mapper.xml中: 注意:#{username}的值不管填什么都不影響占位符賦值,例如:#{aaa}也可以獲取參數(shù)值。但是一般推薦使用屬性名/字段名,提高代碼可閱讀性 select * from t_user where username = #{username} 使用 :需要加單引號’‘,不然會報錯,使用形 式 ′ {}:需要加單引號’ ‘,不然會報錯,使用形式' :需要加單引號’‘,不然會報錯,使用形式′username}',里面的值跟#{}一樣,不受名稱影響 select * from t_user where username = '$username}' 測試: @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserByUsername(admin); sout(user); } 5.2mapper接口方法的參數(shù)為多個 此時,MyBatis會將這些參數(shù)放在一個map集合中,以兩種方式進行存儲 以arg0,arg1,…為鍵,以參數(shù)為值以param0,param1,…為鍵,以參數(shù)為值以上兩種,可以混用,如:arg0,param1方式也可以正常訪問 因此,只需要通過#{}和 以鍵的方式訪問值即可,但是需要注意 {}以鍵的方式訪問值即可,但是需要注意 以鍵的方式訪問值即可,但是需要注意{}的單引號問題。具體使用如下: mapper接口中: //驗證登錄 User checkLogin(String username,String password); mapper.xml中: select * from t_user where username = #{arg0} and password = #{arg1} select * from t_user where username = '${param0}' and password = '${param1}' 測試: @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.checkLogin("admin","123456"); sout(user); } 5.3手動設(shè)置map存儲多參數(shù) 若mapper接口方法的參數(shù)有多個時,可以手動將這些參數(shù)放在一個map中存儲??梢酝ㄟ^KaTeX parse error: Expected 'EOF', got '#' at position 4: {}和#?{}以任意的名稱獲取參數(shù)值,但…{}的單引號問題。具體使用如下: mapper接口中: //驗證登錄(參數(shù)為map) User checkLoginByMap(Map mapper.xml中: select * from t_user where username = #{username} and password = #{password} 測試:在map中設(shè)置訪問的鍵,則SQL中直接用map的鍵即可訪問 @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Map map.put("username",admin"); map.put("password","123456"); User user = mapper.checkLoginByMap(map); sout(user); } 5.4mapper接口方法的參數(shù)是實體類 實際情況中,可能從前端傳值一個對象進行操作,這時mapper接口方法參數(shù)需要是實體類類型 只需要通過KaTeX parse error: Expected 'EOF', got '#' at position 4: {}和#?{}以屬性的方式來訪問屬性值即…{}的單引號問題。具體使用如下: mapper接口中: //添加用戶信息 int insertUser(User user); mapper.xml中: insert into t_user values(null,#{username},#{password},#{age},#{sex},#{email}) 測試: @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int result = mapper.insertUser(null,"李四","123","21","男","123@qq.com"); sout(result); } 5.5使用@Param注解命名多參數(shù) 可以使用@Param注解來自定義多參數(shù)中Map集合訪問的鍵 此時MyBatis會將這些參數(shù)放在一個map集合中,以兩種方式進行存儲 以@Param注解的值為鍵,以參數(shù)為值以param0,param1,…為鍵,以參數(shù)為值 因此只需要通過KaTeX parse error: Expected 'EOF', got '#' at position 4: {}和#?{}以鍵的方式訪問值即可,但是…{}的單引號問題。具體使用如下: mapper接口中: //驗證登錄(使用@param) User checkLoginByParam(@Param("username") String username, @Param("password") String password) mapper.xml中: select * from t_user where username = #{username} and password = #{password} 測試: @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.checkLoginByMap("admin","123456"); sout(user); } 以上五種情況,除了傳輸對象(可直接通過屬性名訪問)外,如果傳輸?shù)氖菃蝹€/多個參數(shù)值時,建議都使用@Param注解來標識鍵,比較便捷 6.MyBatis增刪改查 6.1MyBatis各種查詢 MyBatis的各種查詢功能: 若查詢出的數(shù)據(jù)只有一條 可以通過實體類對象接收可以通過List集合接收【List集合返回值可以為一條數(shù)據(jù)/null,不會報錯】可以通過Map結(jié)合接收:以字段為鍵,字段的值為值 若查詢出的數(shù)據(jù)有多條 可以通過實體類類型的List集合接收 可以通過Map類型的List集合接收 可以在mapper接口的方法上添加@MapKey(“”)注解,此時就可以將每條數(shù)據(jù)轉(zhuǎn)換的map集合作為值,以某個字段的值作為鍵,放在同一個map集合中 注意:一定不能通過實體類對象接收,此時會拋異常TooManyResultsException 6.1.1查詢一個/多個實體類對象 mapper中: //根據(jù)id查詢用戶信息 User getUserById(@Param("id") Integer id); //查詢所有的用戶信息 List mapper.xml中 select * from t_user where id = #{id} select * from t_user 測試類 @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(3); sout(user); } @Test public void testGetAllUser(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List sout(userList); } 6.1.2查詢單行/單列的值 MyBatis中設(shè)置了默認的類型別名,且不區(qū)分大小寫。常用如下: java.lang.Integer–>int, integerint–>_int, _integerMap–>mapString–>string mapper中: //查詢用戶信息的總記錄數(shù) Integer getCount(); mapper.xml中:這里可以直接寫Integer/integer/int/Int都行 select count(*) from t_user 測試類 @Test public void getCount(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int count = mapper.getCount; sout(count); } 6.1.3查詢返回一個/多個Map集合 使用場景:如果我們查詢出來的結(jié)果沒有任何一個實體類可以與之相對應(yīng)(如多表查詢),則可以用Map集合來接收,Map中就是以字段為鍵,以字段的值為值 注意: 查詢多條數(shù)據(jù)時,每條數(shù)據(jù)會存放在一個map中,此時有多個map,不能只用一個map接收,要用List mapper中: //根據(jù)id查詢用戶信息為map集合 Map //查詢所有用戶信息為map集合 List //查詢所有用戶信息為map集合 @MapKey("id") Map mapper.xml中 select * from t_user where id = #{id} select * from t_user select * from t_user 測試類 @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Map sout(map); } @Test public void testGetAllUser(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List sout(mapList); } @Test public void testGetAllUser(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Map sout(map); } 6.2特殊SQL執(zhí)行 6.2.1模糊查詢 mapper中: //根據(jù)用戶名模糊查詢用戶信息 List mapper.xml中: 注意:直接使用’%#{}%'時,#{}不會解析成占位符,會被?代替,被當(dāng)成字符串的一部分,此時沒有占位符,但是我們卻要為占位符賦值,便會直接報錯,可以使用以下三種方式解決: select * from t_user where username like '%${username}%' select * from t_user where username like concat('%',#{username},'%') select * from ${tableName} 測試類 @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List sout(userList); } 6.2.2批量刪除 mapper中: //批量刪除 int deleteMore(@Param("ids") String ids); mapper.xml中 注意:在SQL執(zhí)行過程中,#{}會自動加單引號’ ',但是使用where id in ()時不能加單引號,SQL語句格式不正確,所以只能使用${}來獲取參數(shù),而不能用#{}來獲取參數(shù) delete from t_user where id in (${ids}) 測試類 @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int result = mapper.deleteMore("1,2,3"); sout(result); } 6.2.3動態(tài)設(shè)置表名 mapper中: //查詢指定表中的數(shù)據(jù) List mapper.xml中: 注意:在SQL執(zhí)行過程中,表名是不能加單引號的,所以也不能用#{}來傳參,只能用${} select * from ${tableName} 測試類: @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List sout(userList); } 6.2.4添加功能獲取自增的主鍵 mapper中: //添加用戶信息 void insertUser(); mapper.xml useGeneratedKeys:設(shè)置當(dāng)前標簽中的sql使用了自增的主鍵keyProperty:將自增的主鍵的值賦值給傳輸搭配映射文件中參數(shù)的某個屬性 insert into t_user values(null,#{username},#{password},#{age},#{sex},#{email}) 測試類: @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = new User(null,"張三","123",23,"男","123.@qq.com") mapper.insertUser(user); sout(user); } 7.MyBatis映射關(guān)系 7.1自定義映射resultMap 當(dāng)數(shù)據(jù)庫字段名和實體類屬性值不一致時,例如:數(shù)據(jù)庫中字段使用下劃線連接user_name,而實體類屬性需要使用駝峰命名userName,此時查詢時用userName會顯示null,沒有匹配的字段,無法映射,需要自定義映射 解決字段名和屬性名不一致的情況: 為字段起別名,保持和屬性名一致設(shè)置全局配置,將_自動映射為駝峰:使用時需保證數(shù)據(jù)庫字段符合下劃線命名方式,屬性也符合駝峰命名。通過resultMap解決字段和屬性名的映射關(guān)系 7.1.1通過設(shè)置字段別名解決字段名和屬性名的映射關(guān)系 在xml中的SQL語句中指定字段別名user_name userName來完成映射 select id,user_name userName,age,sex,email from t_user 7.1.2通過全局配置mapUnderscoreToCamelCase解決字段名和屬性名的映射關(guān)系 在mybatis-config.xml中添加settings進行全局配置,來統(tǒng)一將數(shù)據(jù)庫下劃線_字段轉(zhuǎn)換為駝峰形式 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> 7.1.3通過resultMap解決字段和屬性名的映射關(guān)系 使用resultMap標簽可以自定義設(shè)置字段與屬性間的映射關(guān)系 id:唯一標識,不能重復(fù),在SQL語句中的resultMap的值便是設(shè)置的id的值 type:設(shè)置映射關(guān)系中的實體類類型 子標簽: id:設(shè)置主鍵的映射關(guān)系result:設(shè)置普通字段的映射關(guān)系屬性: property:設(shè)置映射關(guān)系中的屬性名,必須是type屬性所設(shè)置的實體類類型中的屬性名,對應(yīng)實體類column:設(shè)置映射關(guān)系中的字段名,必須是SQL語句查詢出的字段名,對應(yīng)數(shù)據(jù)庫 mapper.xml中: select * from t_user 7.2映射關(guān)系:多對一 多對一:對應(yīng)對象,返回一個對象 處理多對一的映射關(guān)系: 級聯(lián)屬性賦值association標簽處理分布查詢,使用較多的方式 7.2.1通過級聯(lián)屬性賦值解決多對一的映射關(guān)系 mapper中: //查詢員工以及員工所對應(yīng)的部門信息 Emp getEmpAndDept(@Param("eid") Integer eid); mapper.xml中: select * from t_emp left join t_dept on t_emp.did = t_dept.did where t_emp.eid = #{eid} 測試類: @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Emp emp = mapper.getEmpAndDept(1); sout(emp); } 7.2.2通過association解決多對一的映射關(guān)系 association:專門處理多對一的映射關(guān)系 property:需要處理的屬性名javaType:該屬性的類型 mapper.xml中: select * from t_emp left join t_dept on t_emp.did = t_dept.did where t_emp.eid = #{eid} 7.2.3通過分布查詢解決多對一的映射關(guān)系 mapper中: //EmpMapper中: //通過分布查詢查詢員工以及員工所對應(yīng)的部門信息 //分布查詢第一步:查詢員工信息 Emp getEmpAndDeptByStepOne(@Param("eid") Integer eid); //DeptMapper中: //通過分布查詢查詢員工以及員工所對應(yīng)的部門信息 //分布查詢第二步,通過did查詢員工所對應(yīng)的部門 Dept getEmpAndDeptByStepTwo(@Param("did") Integer did) mapper.xml中: 使用association屬性引用分步查詢結(jié)果 select:設(shè)置分步查詢的SQL的唯一標識(namespace.SQLId或mapper接口的全類名.方法名)column:設(shè)置分布查詢的條件 select="com.....DeptMapper.getEmpAndDeptByStepTwo" column="did"> select * from t_emp where eid = #{eid} select * from t_dept where did = #{did} 測試類: @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Emp emp = mapper.getEmpAndDeptByStepOne(1); sout(emp); } 7.3延遲加載 分步查詢的優(yōu)點:可以實現(xiàn)延遲加載,但是必須在核心配置文件中設(shè)置全局配置信息 lazyLoadingEnable:表示延遲加載是否可用,延遲加載的全局開關(guān)。當(dāng)開啟時,所有關(guān)聯(lián)對象都會延遲加載 aggressiveLazyLoading:表示是否按需加載。當(dāng)開啟時,任何方法的調(diào)用都會加載該對象的所有屬性,不會延遲加載,且設(shè)成true后lazyLoadingEnable效果丟失,所以要默認false。否則,每個屬性會按需加載 此時就可以實現(xiàn)按需加載,獲取的數(shù)據(jù)是什么,就只會執(zhí)行相應(yīng)的sql。此時可通過association和collection中的fetchType屬性設(shè)置當(dāng)前的分步查詢是否使用延遲加載,fetchType=“l(fā)azy(延遲加載)|eager(立即加載)” 如果要實現(xiàn)延遲加載:查詢員工就只查員工,查詢部門就只查部門,不會關(guān)聯(lián)查詢員工及對應(yīng)部門關(guān)系。需要將lazyLoadingEnable開啟,aggressiveLazyLoading關(guān)閉,然后使用fetchType屬性來實現(xiàn)按需加載 如下:在mybatis-config.xml中設(shè)置 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> mapper.xml中: 使用association屬性引用分步查詢結(jié)果 select:設(shè)置分步查詢的SQL的唯一標識(namespace.SQLId或mapper接口的全類名.方法名)column:設(shè)置分布查詢的條件fetchType:當(dāng)開啟了全局的延遲加載之后,可通過此屬性手動控制延遲加載的效果 fetchType=“l(fā)azy”:表示延遲加載fetchType=“eager”:表示立即加載注意:如果不開啟全局延遲加載,則fetchType不管填什么值都是立即加載的效果 select="com.....DeptMapper.getEmpAndDeptByStepTwo" column="did" fetchType="eager"> select * from t_emp where eid = #{eid} select * from t_dept where did = #{did} 7.4映射關(guān)系:一對多 一對多:對應(yīng)集合,返回一個集合 處理一對多的映射關(guān)系: collection標簽處理分步查詢 7.4.1通過collection解決一對多的映射關(guān)系 Demp實體類中: //用一個集合來表示所有的員工信息 private List get()方法 set()方法 重寫toString()方法 mapper中: //獲取部門以及部門中所有的員工信息 Dept getDeptAndEmp(@Param("did") Integer did); mapper.xml中: collection:處理一對多的映射關(guān)系 ofType:表示該屬性所對應(yīng)的集合中存儲數(shù)據(jù)的類型 select * from t_dept left join t_emp on t_dept.did = t_emp.did where t_dept.did = #{did} 測試類: @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Dept dept = mapper.getDeptAndEmp(1); sout(dept); } 7.4.2通過分步查詢解決一對多的映射關(guān)系 mapper中: //DeptMapper中: //通過分步查詢查詢部門以及部門中所有的員工信息 //分步查詢第一步:查詢部門信息 Dept getDeptAndEmpByStepOne(@Param("did") Integer did); //EmpMapper中: //通過分步查詢查詢部門以及部門中所有的員工信息 //分步查詢第二步:根據(jù)did查詢員工信息 List mapper.xml中: select="com.....EmpMapper.getDeptAndEmpByStepTwo" column="did"> select * from t_dept where did = #{did} select * from t_emp where did = #{did} 測試類: @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Dept dept = mapper.getDeptAndEmp(1); sout(dept); } 8.動態(tài)SQL MyBatis框架的動態(tài)SQL技術(shù)是一種根據(jù)特定條件動態(tài)拼裝SQL語句的功能,它存在的意義是為了解決拼接SQL語句字符串時的痛點問題 8.1if標簽 if標簽可通過test屬性的表達式進行判斷,若表達式的結(jié)果為true,則標簽中的內(nèi)容會執(zhí)行;反之標簽中的內(nèi)容不會執(zhí)行。 if標簽: 根據(jù)標簽中test屬性所對應(yīng)的表達式?jīng)Q定標簽中的內(nèi)容是否需要拼接到SQL中 mapper中: //多條件查詢 List mapper.xml中: where后面加上"1=1"的恒成立條件,避免出現(xiàn)如果第一條if判斷不執(zhí)行時,后面的語句直接執(zhí)行where and報錯 select * from t_emp where 1=1 emp_name = #{empName} and age = #{age} and sex = #{sex} and email = #{email} 測試類: @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Emp emp = mapper.getEmpByCondition(null,"張三",23,"男","123@qq.com"); sout(dept); } 8.2where標簽 上述if標簽中的where關(guān)鍵字是寫死了,避免報錯需要加上一個1=1恒成立條件,但是Mybatis提供where標簽來動態(tài)生成where關(guān)鍵字,還會自動去掉多余的and/or,不用額外加條件 where標簽: 當(dāng)where標簽中有內(nèi)容時,會自動生成where關(guān)鍵字,并且將內(nèi)容前多余的and或or去掉 注意:where標簽不能將其中內(nèi)容后面多余的and或or去掉,使用時最好在前面加and或or 當(dāng)where標簽中沒有內(nèi)容時,此時where標簽沒有任何效果 mapper.xml中: select * from t_emp emp_name = #{empName} and age = #{age} and sex = #{sex} and email = #{email} 8.3trim標簽 上述使用where標簽可以去掉內(nèi)容前面多余的and或or,但是無法去掉內(nèi)容后面多余的and或or,下面可以用trim標簽來實現(xiàn)在內(nèi)容前面或后面添加/去掉指定內(nèi)容 trim標簽: 若標簽中有內(nèi)容時: prefix|suffix:將trim標簽中內(nèi)容前面或后面添加指定內(nèi)容prefixOverrides|suffixOverrides:將trim標簽中內(nèi)容內(nèi)容前面或后面去掉指定內(nèi)容 若標簽中沒有內(nèi)容時:trim標簽也沒有任何效果 mapper.xml中 select * from t_emp emp_name = #{empName} and age = #{age} and sex = #{sex} and email = #{email} 8.4choose、when、otherwise標簽 choose、when、otherwise是一套標簽,相當(dāng)于if…else if…else choose相當(dāng)于父標簽,表示if…else if…else組合 when相當(dāng)于else if,至少要有一個 otherwise相當(dāng)于else,最多只能有一個 mapper中: //測試choose、when、otherwise List mapper.xml中: 注意:只會執(zhí)行滿足條件的一條when,不用加and或or select * from t_emp emp_name = #{empName} age = #{age} sex = #{sex} email = #{email} did = 1 測試類: @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List sout(empList); } 8.5foreach標簽 用來做循環(huán)操作,如批量刪除或批量添加 foreeach標簽: collection:設(shè)置需要循環(huán)的數(shù)組或集合item:表示數(shù)組或集合中的每一個數(shù)據(jù)separator:循環(huán)體之間的分隔符open:foreach標簽所循環(huán)的所有內(nèi)容的開始符close:foreach標簽所循環(huán)的所有內(nèi)容的結(jié)束符 mapper中: //通過數(shù)組實現(xiàn)批量刪除 int deleteMoreByArray(@Param("eids") Integer[] eids); //通過List集合實現(xiàn)批量添加 int insertMoreByList(@Param("emps") List mapper.xml中: delete from t_emp where eid in ( #{eid} ) delete from t_emp where eid in #{eid} delete from t_emp where eid = #{eid} insert into t_emp values (null,#{emp.empName},#{emp.age},#{emp.sex},#{emp.email},null) 測試類: @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int result = mapper.deleteMoreByArray(new Integer[]{6,7,8}); sout(result); } @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Emp emp1 = new Emp(null,"a1",23,"男","123@qq.com"); Emp emp2 = new Emp(null,"a2",23,"男","123@qq.com"); Emp emp3 = new Emp(null,"a3",23,"男","123@qq.com"); List int result = mapper.insertMoreByList(emps); sout(result); } 8.6sql標簽 將常用的sql片段拿出來進行記錄,當(dāng)需要用的時候直接引用 sql標簽: 設(shè)置sql片段:eid,emp_name,age,sex,email引用sql片段: mapper.xml中: eid,emp_name,age,sex,email select emp_name = #{empName} and age = #{age} and sex = #{sex} and email = #{email} 9.MyBatis緩存 將當(dāng)前查詢出的數(shù)據(jù)進行記錄,等下一次再查詢相同數(shù)據(jù)的時候,直接從緩存中取,不用重新訪問數(shù)據(jù)庫 MyBatis中的緩存分為一級緩存和二級緩存,一級緩存是默認開啟的 9.1一級緩存SqlSession 一級緩存是SqlSession級別的,通過同一個SqlSession查詢的數(shù)據(jù)會被緩存,下次查詢相同的數(shù)據(jù),就會從緩存中直接獲取,不會從數(shù)據(jù)庫重新訪問 如:使用同一個SqlSession連續(xù)查詢相同的數(shù)據(jù),則只會執(zhí)行一條SQL,其余的數(shù)據(jù)從緩存中拿取返回 @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Emp emp1 = mapper.getEmpById(1); sout(emp1); Emp emp2 = mapper.getEmpById(1); sout(emp2); } //執(zhí)行效果:一條SQL語句,兩條打印結(jié)果(emp1,emp2),后面那條是直接從緩存拿的,不用重新執(zhí)行一次SQL 使一級緩存失效的四種情況: 不同的SqlSession對應(yīng)不同的一級緩存 同一個SqlSession但是查詢條件不同 同一個SqlSession兩次查詢期間執(zhí)行了任何一次增刪改操作 同一個SqlSession兩次查詢期間手動清空了緩存:使用sqlSession.clearCache()方法 @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Emp emp1 = mapper.getEmpById(1); sout(emp1); //清空緩存 sqlSession.clearCache() Emp emp2 = mapper.getEmpById(1); sout(emp2); } //執(zhí)行效果:一條SQL,一條打印數(shù)據(jù);再一條SQL,再一條打印數(shù)據(jù) 9.2二級緩存SqlSessionFactory 二級緩存的范圍比一級緩存的范圍要大一些,且需要手動設(shè)置 9.2.1二級緩存概念 二級緩存是SqlSessionFactory級別的,通過同一個SqlSessionFactory創(chuàng)建的SqlSession查詢的結(jié)果會被緩存;此后若再次執(zhí)行相同的查詢語句,結(jié)果就會從緩存中獲取 二級緩存開啟的條件:4個條件缺一不可 在核心配置文件鐘工,設(shè)置全局配置屬性cacheEnabled=“true”,默認為true,不需要設(shè)置在映射文件中設(shè)置標簽,直接放在mapper.xml文件中即可二級緩存必須在SqlSession關(guān)閉或提交之后有效查詢的數(shù)據(jù)所轉(zhuǎn)換的實體類類型必須實現(xiàn)序列化的接口,implements Serializable 使二級緩存失效的情況: 唯一情況:兩次查詢之間執(zhí)行了任意的增刪改,會使一級和二級緩存同時失效注意:sqlSession.clearCache()手動清空緩存只對一級緩存有效,無法使二級緩存失效 9.2.2二級緩存功能用法 二級緩存的用法測試如下: 全局配置中:默認cacheEnabled=“true”,不需要特別設(shè)置 實體類中:需要實現(xiàn)序列化接口 public class Emp implements Serializable{} mapper.xml中:直接使用標簽來開啟二級緩存 select * ....... 需要測試二級緩存,此時就不要使用封裝SqlSessionUtils工具類了,在測試方法中重新實現(xiàn),一個sqlSessionFactory對應(yīng)創(chuàng)建多個sqlSession來進行測試 注意:每個sqlSession執(zhí)行完后必須使用sqlSession.close()來關(guān)閉才會有效,否則緩存命中率Cache Hit Ratio為0,二級緩存無效;加上sqlSession.close()后,第二個sqlSession的緩存命中率Cache Hit Ratio為0.5,不需要重新執(zhí)行SQL,從二級緩存中拿取數(shù)據(jù)。 @Test public void testCache() throws IOException{ try{ InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession1 = sqlSessionFactory.openSession(true); CacheMapper mapper1 = sqlSession1.getMapper(CacheMapper.class); sout(mapper1.getEmpById(1)); sqlSession1.close();//需要關(guān)閉或提交后二級緩存才會有效,否則緩存命中率Cache Hit Ratio為0 SqlSession sqlSession2 = sqlSessionFactory.openSession(true); CacheMapper mapper2 = sqlSession2.getMapper(CacheMapper.class); sout(mapper1.getEmpById(1)); sqlSession2.close(); } catch(IOException e){ e.printStackTrace(); } } 9.2.3二級緩存相關(guān)配置 在mapper配置文件中添加的cache標簽可以設(shè)置一些屬性: eviction屬性:緩存回收策略 LRU(Least Recently Used)-最近最少使用的:移除最長時間不被使用的對象FIFO(Fist in First out)-先進先出:按對象進入緩存的順序來移除它們SOFT -軟引用:移除基于垃圾回收器狀態(tài)和軟引用規(guī)則的對象WEAK -弱引用:更積極地移除基于垃圾收集器狀態(tài)和弱引用規(guī)則的對象 默認的是LRU flushInterval屬性:刷新間隔,單位毫秒 默認情況是不設(shè)置,也就是沒有刷新間隔,緩存僅僅調(diào)用語句時刷新 size屬性:引用數(shù)目,正整數(shù) 代表緩存最多可以存儲多少個對象,太大容易導(dǎo)致內(nèi)存溢出 readOnly屬性:只讀,true/false true:只讀緩存;會給所有調(diào)用者返回緩存對象的相同實例。因此這些對象不能被修改,這提供了很重要的性能優(yōu)勢false:讀寫緩存;會返回緩存對象的拷貝(通過序列化)。這會慢一些,但是安全,因此默認是false 9.3緩存查詢順序 MyBatis緩存查詢的順序如下: 先查詢二級緩存,因為二級緩存中可能會有其他程序已經(jīng)查出來的數(shù)據(jù),可以拿來直接使用如果二級緩存沒有命中,再查詢一級緩存如果一級緩存也沒有命中,則查詢數(shù)據(jù)庫SqlSession關(guān)閉之后,一級緩存中的數(shù)據(jù)會寫入二級緩存 9.4整合第三方緩存EHCache MyBatis是持久層框架,做緩存不太專業(yè),提供了第三方接口來做二級緩存,但是一級緩存還是原生 9.4.1依賴導(dǎo)入 引入依賴: 各jar包功能: mybatis-ehcache:MyBatis和EHCache的整合包ehcache:EHCache核心包slf4j-api:SLF4J日志門面包logback-classic:支持SLF4J門面接口的一個具體實現(xiàn) 9.4.2EHCache配置 創(chuàng)建EHCache的配置文件ehcache.xml xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"> maxElementsInMemory="10000" maxElementsOnDisk="10000000" eternal="false" overflowToDisk="true" timeToIdleSeconds="120" timeToLiveSeconds="120" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> 在mapper.xml文件中使用設(shè)置type類型為EHCache緩存,不設(shè)置則默認使用MyBatis原生的二級緩存 9.4.3加入logback日志 存在SLF4J時,作為簡易日志的log4j將失效,此時我們需要借助SLF4J的具體實現(xiàn)logback來打印日志 創(chuàng)建logback的配置文件logback.xml 到此,第三方緩存就配置完成了,像以前使用MyBatis原生的緩存一樣使用即可,示例詳見原二級緩存的使用 10.MyBatis逆向工程 10.1正向/逆向工程 正向工程:先創(chuàng)建Java實體類,由框架負責(zé)根據(jù)實體類生成數(shù)據(jù)庫表。Hibernate是支持正向工程的 逆向工程:先創(chuàng)建數(shù)據(jù)庫表,由框架負責(zé)根據(jù)數(shù)據(jù)庫表,反向生成如下資源: Java實體類Mapper接口Mapper映射文件 逆向工程主要用來自動生成代碼 10.2逆向工程的配置&使用 添加依賴和插件: 創(chuàng)建配置文件:文件名必須是generatorConfig.xml PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> connectionURL="jdbc:mysql://127.0.0.1:3306/mybatis" userId="root" password="123456"> SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(true); EmpMapper mapper = sqlSession.getMapper(EmpMapper.class); //查詢所有數(shù)據(jù),無條件查詢,傳入值為null List list.foreach(emp->sout(emp)); //根據(jù)條件查詢,首先創(chuàng)建一個EmpExample EmpExample example = new EmpExample(); //使用createCriteria()創(chuàng)造條件,后面帶上字段條件,且可以通過.鏈式結(jié)構(gòu)一直加條件,下面表示查詢姓名為“張三”且年齡大于等于20的信息 example.createCriteria().andEmpNameEqualTo("張三").andAgeGreaterThanOrEqualTo(20); //如果想用or條件,直接用or(),后面繼續(xù)跟andXXX條件,即表示與上一個條件是or關(guān)系 example.or().andDidIsNotNull(); //將example放入查詢中,即實現(xiàn)帶條件查詢 List list.foreach(emp->sout(emp)); } catch(IOException e){ e.printStackTrace(); } } 奢華尊享版修改功能測試: @Test public void test() throws IOException{ try{ InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(true); EmpMapper mapper = sqlSession.getMapper(EmpMapper.class); //根據(jù)主鍵進行修改 mapper.uodateByPrimaryKey(1,"admin",22,null,"456@qq,com");//null也會直接修改null mapper.uodateByPrimaryKeySelective(1,"admin",22,null,"456@qq,com");//選擇性修改,null不會修改,直接忽略 } catch(IOException e){ e.printStackTrace(); } } 11.MyBatis分頁插件 11.1分頁插件使用步驟 導(dǎo)入依賴: 配置分頁插件: 在MyBatis的核心配置文件中配置插件 11.2分頁插件的使用 數(shù)據(jù)庫分頁查詢關(guān)鍵字:limit index,pageSize MyBatis分頁插件使用:page(pageNum,pageSize) index:當(dāng)前頁的起始索引pageSize:每頁顯示的條數(shù)pageNum:當(dāng)前頁的頁碼index=(pageNum-1)*pageSize 使用MyBatis的分頁插件實現(xiàn)分頁功能: 需要在查詢功能之前開啟分頁: PageHelper.startPage(int pageNum,int pageSize); 在查詢分頁之后獲取分頁相關(guān)信息: PageInfo page = new PageInfo<>(list,5); list:表示分頁數(shù)據(jù)5:表示當(dāng)前導(dǎo)航分頁的數(shù)據(jù),顯示5個導(dǎo)航分頁,建議奇數(shù),左邊展示2個,右邊展示2個 常用數(shù)據(jù): pageNum:當(dāng)前頁的頁碼pageSize:每頁顯示的條數(shù)size:當(dāng)前頁顯示的條數(shù)total:總記錄數(shù)pages:頁數(shù)prePage:上一頁的頁碼nextPage:下一頁的頁碼isFirstPage/isLastPage:是否為第一頁/最后一頁hasPreviousPage/hasNextPage:是否存在上一頁/下一頁navigatePage:導(dǎo)航分頁的頁碼數(shù)navigatepageNums:導(dǎo)航分頁的頁碼,[1,2,3,4,5] @Test public void test() throws IOException{ try{ InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(true); EmpMapper mapper = sqlSession.getMapper(EmpMapper.class); //查詢之前開啟分頁插件,訪問第1頁,顯示4條數(shù)據(jù),返回值是一個page對象 PageHelper.startPage(1,4); List PageInfo list.foreach(emp->sout(emp)); } catch(IOException e){ e.printStackTrace(); } } public void test() throws IOException{ try{ InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(true); EmpMapper mapper = sqlSession.getMapper(EmpMapper.class); //根據(jù)主鍵進行修改 mapper.uodateByPrimaryKey(1,"admin",22,null,"456@qq,com");//null也會直接修改null mapper.uodateByPrimaryKeySelective(1,"admin",22,null,"456@qq,com");//選擇性修改,null不會修改,直接忽略 } catch(IOException e){ e.printStackTrace(); } } 11.MyBatis分頁插件 11.1分頁插件使用步驟 導(dǎo)入依賴: 配置分頁插件: 在MyBatis的核心配置文件中配置插件 11.2分頁插件的使用 數(shù)據(jù)庫分頁查詢關(guān)鍵字:limit index,pageSize MyBatis分頁插件使用:page(pageNum,pageSize) index:當(dāng)前頁的起始索引pageSize:每頁顯示的條數(shù)pageNum:當(dāng)前頁的頁碼index=(pageNum-1)*pageSize 使用MyBatis的分頁插件實現(xiàn)分頁功能: 需要在查詢功能之前開啟分頁: PageHelper.startPage(int pageNum,int pageSize); 在查詢分頁之后獲取分頁相關(guān)信息: PageInfo page = new PageInfo<>(list,5); list:表示分頁數(shù)據(jù)5:表示當(dāng)前導(dǎo)航分頁的數(shù)據(jù),顯示5個導(dǎo)航分頁,建議奇數(shù),左邊展示2個,右邊展示2個 常用數(shù)據(jù): pageNum:當(dāng)前頁的頁碼pageSize:每頁顯示的條數(shù)size:當(dāng)前頁顯示的條數(shù)total:總記錄數(shù)pages:頁數(shù)prePage:上一頁的頁碼nextPage:下一頁的頁碼isFirstPage/isLastPage:是否為第一頁/最后一頁hasPreviousPage/hasNextPage:是否存在上一頁/下一頁navigatePage:導(dǎo)航分頁的頁碼數(shù)navigatepageNums:導(dǎo)航分頁的頁碼,[1,2,3,4,5] @Test public void test() throws IOException{ try{ InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(true); EmpMapper mapper = sqlSession.getMapper(EmpMapper.class); //查詢之前開啟分頁插件,訪問第1頁,顯示4條數(shù)據(jù),返回值是一個page對象 PageHelper.startPage(1,4); List PageInfo list.foreach(emp->sout(emp)); } catch(IOException e){ e.printStackTrace(); } } 柚子快報激活碼778899分享:Mybatis筆記 好文閱讀 本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點和立場。 轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。 請在主題配置——文章設(shè)置里上傳 掃描二維碼手機訪問您暫未設(shè)置收款碼