MyBatis注解CRUD與執(zhí)行流程深入探究
結(jié)果映射ResultMap
引入resultMap–MyBatis中最強(qiáng)大的元素
數(shù)據(jù)庫(kù)字段名::
實(shí)體類字段名:
public class User { private int id; private String name; private String password;
如上所示,當(dāng)sql的字段名與實(shí)體類沖突時(shí)測(cè)試結(jié)果:
User{id=1, name='張三', password='null'} User{id=2, name='李四', password='null'} User{id=3, name='王五', password='null'}
解決方案一:在sql語(yǔ)句中為字段起別名
select id,name,pwd as password from mybatis.user;
解決方案二:結(jié)果集映射ReaultMap
<resultMap id="UserMap" type="User" > <result column="pwd" property="password"/> </resultMap> <select id="getUserList" resultMap="UserMap"> select * from mybatis.user; </select>
resultMap中的id對(duì)應(yīng)具體的sql操作的resultMap屬性,在映射時(shí)只需設(shè)置子標(biāo)簽result的column(sql的列、字段名)映射到實(shí)體類的名稱屬性property便可以成功操作
概括來講就是:將數(shù)據(jù)庫(kù)中的列映射到實(shí)體類具體的某一字段
MyBatis 會(huì)在幕后自動(dòng)創(chuàng)建一個(gè) ResultMap
,再根據(jù)屬性名來映射列到 JavaBean 的屬性上 。這就是上述示例代碼中,因?yàn)樽侄蚊麤_突無(wú)法正確查詢到password的原因
日志工廠
MyBatis的配置當(dāng)中settings設(shè)置了內(nèi)置的日志工廠,但需要開發(fā)人員在使用時(shí)指定具體的日志實(shí)現(xiàn)。
MyBatis內(nèi)置日志工廠: SLF4J | LOG4J(3.5.9 起廢棄) | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING
STDOUT_LOGGING在settings中配置后直接就可以運(yùn)行使用,不需要額外的properties等配置文件
STDOUT_LOGGING
配置信息:
<settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings>
打印出來一堆日志,我們只用看下面的具體執(zhí)行信息即可
-- 表示正在創(chuàng)建連接
Created connection 1346201722.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@503d687a]
-- 當(dāng)前執(zhí)行的sql
==> Preparing: select * from mybatis.user;
-- 參數(shù)
==> Parameters:
-- sql中的字段名
<== Columns: id, name, pwd
-- 所查詢到的數(shù)據(jù) 三行數(shù)據(jù)
<== Row: 1, 張三, 123
<== Row: 2, 李四, 234
<== Row: 3, 王五, 345
-- 數(shù)據(jù)總數(shù)
<== Total: 3
-- 打印結(jié)果
User{id=1, name='張三', password='123'}
User{id=2, name='李四', password='234'}
User{id=3, name='王五', password='345'}
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@503d687a]
-- 關(guān)閉連接
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@503d687a]
-- 將連接回收
Returned connection 1346201722 to pool.Process finished with exit code 0
LOG4J
配置文件:
<settings> <setting name="logImpl" value="LOG4J"/> </settings>
log4j.properties
# 將等級(jí)為DEBUG的日志信息輸出到控制臺(tái)(console)、文件(file)兩個(gè)目的地
log4j.rootLogger=DEBUG,console,file# 輸出到控制臺(tái)的相關(guān)設(shè)置
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.Target=System.out
log4j.appender.console.Encoding=UTF-8
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%p]%d{yyyy-MM-dd HH:mm:ss} %l - %m%n# 輸出到文件的相關(guān)設(shè)置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File = ./log/test.log
log4j.appender.file.Threshold = DEBUG
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern = [%c]-%m%n# 設(shè)置日志的輸出級(jí)別
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
注解開發(fā)CRUD
mybatis注解開發(fā)通常用于簡(jiǎn)單的sql執(zhí)行,較復(fù)雜的sql還是需要用xml文件進(jìn)行配置。
注解開發(fā)示例:
在接口中針對(duì)方法配置對(duì)應(yīng)的sql注解
@Select("select * from user") List<User> getUsers();
在mybatis-config.xml中配置
<!-- 注冊(cè)接口mapper --> <mappers> <mapper class="com.yuqu.dao.UserMapper"/> </mappers>
CRUD:
// 增 @Insert("insert into user (id,name,pwd) values(#{id},#{name},#{password})") int insertUser(User user); // 刪 @Delete("delete from user where id = #{nb}") int deleteUser(@Param("nb") int id); // 改 @Update("update user set name=#{name},pwd=#{password} where id = #{id}") int updateUser(Map<String,Object> map); // 查詢?nèi)? @Select("select id,name,pwd as password from user") List<User> getUsers();
關(guān)于@Param
注解:
基本數(shù)據(jù)類型或String類型需要加Param注解
引用類型不需要
只有一個(gè)基本數(shù)據(jù)類型可以不加,但建議加上
在sql中引用的變量名就是@Param中命名的參數(shù)
如:
@Delete("delete from user where id = #{nb}") int deleteUser(@Param("nb") int id);
MyBatis執(zhí)行流程
- Resources加載全局配置文件–> mybatis-config.xml
String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource);
- 實(shí)例化SqlSessionFactoryBuilder構(gòu)造器
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- build解析配置文件流
// 以下為SqlSessionFactoryBuilder源碼 XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
可以看到,build方法將輸入流、環(huán)境、屬性一一解析到Cconfiguration中
- 實(shí)例化SqlSessionFactory
- transactionalCaches事務(wù)管理器
- 創(chuàng)建executor執(zhí)行器
- 創(chuàng)建SqlSession實(shí)例
public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); }
- 實(shí)現(xiàn)CRUD
- 判斷是否執(zhí)行成功
- 執(zhí)行成功提交事務(wù)
- 執(zhí)行失敗則跳轉(zhuǎn)到事務(wù)管理器重新進(jìn)行
到此這篇關(guān)于MyBatis注解CRUD與執(zhí)行流程深入探究的文章就介紹到這了,更多相關(guān)MyBatis注解CRUD內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot中非容器類如何獲取配置文件數(shù)據(jù)
這篇文章主要介紹了springboot中非容器類如何獲取配置文件數(shù)據(jù)問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01Apache?Log4j2?報(bào)核彈級(jí)漏洞快速修復(fù)方法
Apache?Log4j2?是一個(gè)基于Java的日志記錄工具,是?Log4j?的升級(jí),是目前最優(yōu)秀的?Java日志框架之一,這篇文章主要介紹了突發(fā)Apache?Log4j2?報(bào)核彈級(jí)漏洞快速修復(fù)方法,需要的朋友可以參考下2021-12-12Java多線程Callable接口實(shí)現(xiàn)代碼示例
相信大家對(duì)Java編程中如何創(chuàng)建線程已經(jīng)不陌生了,這篇文章就向朋友們介紹實(shí)現(xiàn)callable接口,具體實(shí)例詳見正文。2017-10-10關(guān)于SpringSecurity認(rèn)證邏輯源碼分析
這篇文章主要介紹了關(guān)于SpringSecurity認(rèn)證邏輯源碼分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07Retrofit+RxJava實(shí)現(xiàn)帶進(jìn)度條的文件下載
這篇文章主要為大家詳細(xì)介紹了Retrofit+RxJava實(shí)現(xiàn)帶進(jìn)度條的文件下載,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-06-06BeanDefinitionRegistryPostProcessor如何動(dòng)態(tài)注冊(cè)Bean到Spring
這篇文章主要介紹了BeanDefinitionRegistryPostProcessor如何動(dòng)態(tài)注冊(cè)Bean到Spring,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03eclipse創(chuàng)建一個(gè)基于maven的web項(xiàng)目詳細(xì)步驟
開始學(xué)習(xí)maven,并用maven創(chuàng)建了第一個(gè)屬于自己的web項(xiàng)目,下面這篇文章主要給大家介紹了關(guān)于eclipse創(chuàng)建一個(gè)基于maven的web項(xiàng)目的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12