一、新建項目及配置
1.1 新建一個SpringBoot項目,并在pom.xml下加入以下代碼
<dependency>
<groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.0.1</version></dependency>
application.properties文件下配置(使用的是MySql數據庫)
# 注:我的SpringBoot 是2.0以上版本,數據庫驅動如下
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/database?characterEncoding=utf8&serverTimezone=UTC spring.datasource.username=your_username spring.datasource.password=your_password
# 可將 com.dao包下的dao接口的SQL語句打印到控制臺,學習MyBatis時可以開啟
logging.level.com.dao=debug
SpringBoot啟動類Application.java 加入@SpringBootApplication 注解即可(一般使用該注解即可,它是一個組合注解)
@SpringBootApplication public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);} }
之后dao層的接口文件放在Application.java 能掃描到的位置即可,dao層文件使用@Mapper注解
@Mapper public interface UserDao {/*** 測試連接*/@Select("select 1 from dual")int testSqlConnent(); }
測試接口能返回數據即表明連接成功
二、簡單的增刪查改sql語句
2.1 傳入參數
(1) 可以傳入一個JavaBean
(2) 可以傳入一個Map
(3) 可以傳入多個參數,需使用@Param("ParamName") 修飾參數
2.2 Insert,Update,Delete 返回值
接口方法返回值可以使用 void 或 int,int返回值代表影響行數
2.3 Select 中使用@Results 處理映射
查詢語句中,如何名稱不一致,如何處理數據庫字段映射到Java中的Bean呢?
(1)?可以使用sql 中的as 對查詢字段改名,以下可以映射到User 的 name字段
@Select("select "1" as name from dual")User testSqlConnent();
(2)?使用?@Results,有 @Result(property="Java Bean name", column="DB column name"), 例如:
@Select("select t_id, t_age, t_name "+ "from sys_user "+ "where t_id = #{id} ")@Results(id="userResults", value={@Result(property="id", column="t_id"),@Result(property="age", column="t_age"),@Result(property="name", column="t_name"),})
User selectUserById(@Param("id") String id);
對于resultMap 可以給與一個id,其他方法可以根據該id 來重復使用這個resultMap。例如:
@Select("select t_id, t_age, t_name "+ "from sys_user "+ "where t_name = #{name} ")@ResultMap("userResults")User selectUserByName(@Param("name") String name);
2.4 注意一點,關于JavaBean 的構造器問題
我在測試的時候,為了方便,給JavaBean 添加了一個帶參數的構造器。后面在測試resultMap 的映射時,發現把映射關系@Results 注釋掉,返回的bean 還是有數據的;更改查詢字段順序時,出現?java.lang.NumberFormatException: For input string: "hello"的異常。經過測試,發現是bean 的構造器問題。并有以下整理:
(1) bean 只有一個有參的構造方法,MyBatis 調用該構造器(參數按順序),此時@results 注解無效。并有查詢結果個數跟構造器不一致時,報異常。
(2)?bean 有多個構造方法,且沒有 無參構造器,MyBatis 調用跟查詢字段數量相同的構造器;若沒有數量相同的構造器,則報異常。
(3)?bean 有多個構造方法,且有 無參構造器,?MyBatis?調用無參數造器。
(4) 綜上,一般情況下,bean 不要定義有參的構造器;若需要,請再定義一個無參的構造器。
2.5 簡單查詢例子
/*** 測試連接*/@Select("select 1 from dual")int testSqlConnent();/*** 新增,參數是一個bean*/@Insert("insert into sys_user "+ "(t_id, t_name, t_age) "+ "values "+ "(#{id}, #{name}, ${age}) ")int insertUser(User bean);/*** 新增,參數是一個Map*/@Insert("insert into sys_user "+ "(t_id, t_name, t_age) "+ "values "+ "(#{id}, #{name}, ${age}) ")int insertUserByMap(Map<String, Object> map);/*** 新增,參數是多個值,需要使用@Param來修飾* MyBatis 的參數使用的@Param的字符串,一般@Param的字符串與參數相同*/@Insert("insert into sys_user "+ "(t_id, t_name, t_age) "+ "values "+ "(#{id}, #{name}, ${age}) ")int insertUserByParam(@Param("id") String id, @Param("name") String name,@Param("age") int age);/*** 修改*/@Update("update sys_user set "+ "t_name = #{name}, "+ "t_age = #{age} "+ "where t_id = #{id} ")int updateUser(User bean);/*** 刪除*/@Delete("delete from sys_user "+ "where t_id = #{id} ")int deleteUserById(@Param("id") String id);/*** 刪除*/@Delete("delete from sys_user ")int deleteUserAll();/*** truncate 返回值為0*/@Delete("truncate table sys_user ")void truncateUser();/*** 查詢bean* 映射關系@Results* @Result(property="java Bean name", column="DB column name"),*/@Select("select t_id, t_age, t_name "+ "from sys_user "+ "where t_id = #{id} ")@Results(id="userResults", value={@Result(property="id", column="t_id"),@Result(property="age", column="t_age"),@Result(property="name", column="t_name", javaType = String.class),})User selectUserById(@Param("id") String id);/*** 查詢List*/@ResultMap("userResults")@Select("select t_id, t_name, t_age "+ "from sys_user ")List<User> selectUser();@Select("select count(*) from sys_user ")int selectCountUser();
三、MyBatis動態SQL
注解版下,使用動態SQL需要將sql語句包含在script標簽里
<script></script>
3.1 if
通過判斷動態拼接sql語句,一般用于判斷查詢條件
<if test=''>...</if>
3.2?choose
根據條件選擇
<choose><when test=''> ...</when><when test=''> ...</when><otherwise> ...</otherwise> </choose>
3.3 where,set
一般跟if 或choose 聯合使用,這些標簽或去掉多余的 關鍵字 或 符號。如
<where><if test="id != null "> and t_id = #{id}</if> </where>
若id為null,則沒有條件語句;若id不為 null,則條件語句為 where t_id = ??
<where> ... </where> <set> ... </set>
3.4?bind
綁定一個值,可應用到查詢語句中
<bind name="" value="" />
3.5 foreach
循環,可對傳入和集合進行遍歷。一般用于批量更新和查詢語句的 in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">#{item}
</foreach>
(1) item:集合的元素,訪問元素的Filed 使用 #{item.Filed}
(2) index: 下標,從0開始計數
(3) collection:傳入的集合參數
(4) open:以什么開始
(5) separator:以什么作為分隔符
(6) close:以什么結束
例如 傳入的list 是一個 List<String>: ["a","b","c"],則上面的 foreach 結果是: ("a", "b", "c")
3.6 動態SQL例子
/*** if 對內容進行判斷* 在注解方法中,若要使用MyBatis的動態SQL,需要編寫在<script></script>標簽內* 在 <script></script>內使用特殊符號,則使用java的轉義字符,如 雙引號 "" 使用"" 代替* concat函數:mysql拼接字符串的函數*/@Select("<script>"+ "select t_id, t_name, t_age "+ "from sys_user "+ "<where> "+ " <if test='id != null and id != ""'> "+ " and t_id = #{id} "+ " </if> "+ " <if test='name != null and name != ""'> "+ " and t_name like CONCAT('%', #{name}, '%') "+ " </if> "+ "</where> "+ "</script> ")@Results(id="userResults", value={@Result(property="id", column="t_id"),@Result(property="name", column="t_name"),@Result(property="age", column="t_age"),})List<User> selectUserWithIf(User user);/*** choose when otherwise 類似Java的Switch,選擇某一項* when...when...otherwise... == if... if...else... */@Select("<script>"+ "select t_id, t_name, t_age "+ "from sys_user "+ "<where> "+ " <choose> "+ " <when test='id != null and id != ""'> "+ " and t_id = #{id} "+ " </when> "+ " <otherwise test='name != null and name != ""'> "+ " and t_name like CONCAT('%', #{name}, '%') "+ " </otherwise> "+ " </choose> "+ "</where> "+ "</script> ")@ResultMap("userResults")List<User> selectUserWithChoose(User user);/*** set 動態更新語句,類似<where>*/@Update("<script> "+ "update sys_user "+ "<set> "+ " <if test='name != null'> t_name=#{name}, </if> "+ " <if test='age != null'> t_age=#{age}, </if> "+ "</set> "+ "where t_id = #{id} "+ "</script> ")int updateUserWithSet(User user);/*** foreach 遍歷一個集合,常用于批量更新和條件語句中的 IN* foreach 批量更新*/@Insert("<script> "+ "insert into sys_user "+ "(t_id, t_name, t_age) "+ "values "+ "<foreach collection='list' item='item' "+ " index='index' separator=','> "+ "(#{item.id}, #{item.name}, #{item.age}) "+ "</foreach> "+ "</script> ")int insertUserListWithForeach(List<User> list);/*** foreach 條件語句中的 IN*/@Select("<script>"+ "select t_id, t_name, t_age "+ "from sys_user "+ "where t_name in "+ " <foreach collection='list' item='item' index='index' "+ " open='(' separator=',' close=')' > "+ " #{item} "+ " </foreach> "+ "</script> ")@ResultMap("userResults")List<User> selectUserByINName(List<String> list);/*** bind 創建一個變量,綁定到上下文中*/@Select("<script> "+ "<bind name=\"lname\" value=\"'%' + name + '%'\" /> "+ "select t_id, t_name, t_age "+ "from sys_user "+ "where t_name like #{lname} "+ "</script> ")@ResultMap("userResults")List<User> selectUserWithBind(@Param("name") String name);
?
四、MyBatis 對一,對多查詢
首先看@Result注解源碼
public @interface Result {boolean id() default false;String column() default "";String property() default "";Class<?> javaType() default void.class;JdbcType jdbcType() default JdbcType.UNDEFINED;Class<? extends TypeHandler> typeHandler() default UnknownTypeHandler.class;One one() default @One;Many many() default @Many; }
可以看到有兩個注解 @One 和 @Many,MyBatis就是使用這兩個注解進行對一查詢和對多查詢
@One 和 @Many寫在@Results 下的 @Result 注解中,并需要指定查詢方法名稱。具體實現看以下代碼
// User Bean的屬性 private String id; private String name; private int age; private Login login; // 每個用戶對應一套登錄賬戶密碼 private List<Identity> identityList; // 每個用戶有多個證件類型和證件號碼// Login Bean的屬性 private String username; private String password;// Identity Bean的屬性 private String idType; private String idNo;
/*** 對@Result的解釋* property: java bean 的成員變量* column: 對應查詢的字段,也是傳遞到對應子查詢的參數,傳遞多參數使用Map column = "{param1=SQL_COLUMN1,param2=SQL_COLUMN2}"* one=@One: 對一查詢* many=@Many: 對多查詢* select: 需要查詢的方法,全稱或當前接口的一個方法名
* fetchType.EAGER: 急加載*/@Select("select t_id, t_name, t_age "+ "from sys_user "+ "where t_id = #{id} ")@Results({@Result(property="id", column="t_id"),@Result(property="name", column="t_name"),@Result(property="age", column="t_age"),@Result(property="login", column="t_id",one=@One(select="com.github.mybatisTest.dao.OneManySqlDao.selectLoginById", fetchType=FetchType.EAGER)),@Result(property="identityList", column="t_id",many=@Many(select="selectIdentityById", fetchType=FetchType.EAGER)),})User2 selectUser2(@Param("id") String id);/*** 對一 子查詢*/@Select("select t_username, t_password "+ "from sys_login "+ "where t_id = #{id} ")@Results({@Result(property="username", column="t_username"),@Result(property="password", column="t_password"),})Login selectLoginById(@Param("id") String id);/*** 對多 子查詢*/@Select("select t_id_type, t_id_no "+ "from sys_identity "+ "where t_id = #{id} ")@Results({@Result(property="idType", column="t_id_type"),@Result(property="idNo", column="t_id_no"),})List<Identity> selectIdentityById(@Param("id") String id);
測試結果,可以看到只調用一個方法查詢,相關對一查詢和對多查詢也會一并查詢出來
// 測試類代碼 @Testpublic void testSqlIf() {User2 user = dao.selectUser2("00000005");System.out.println(user);System.out.println(user.getLogin());System.out.println(user.getIdentityList());} // 查詢結果User2 [id=00000005, name=name_00000005, age=5]Login [username=the_name, password=the_password][Identity [idType=01, idNo=12345678], Identity [idType=02, idNo=987654321]]
五、MyBatis開啟事務
5.1 使用?@Transactional 注解開啟事務
@Transactional標記在方法上,捕獲異常就rollback,否則就commit。自動提交事務。
/*** @Transactional 的參數* value |String | 可選的限定描述符,指定使用的事務管理器* propagation |Enum: Propagation | 可選的事務傳播行為設置* isolation |Enum: Isolation | 可選的事務隔離級別設置* readOnly |boolean | 讀寫或只讀事務,默認讀寫* timeout |int (seconds) | 事務超時時間設置* rollbackFor |Class<? extends Throwable>[] | 導致事務回滾的異常類數組* rollbackForClassName |String[] | 導致事務回滾的異常類名字數組* noRollbackFor |Class<? extends Throwable>[] | 不會導致事務回滾的異常類數組* noRollbackForClassName |String[] | 不會導致事務回滾的異常類名字數組*/@Transactional(timeout=4)public void testTransactional() {// dosomething..
}
5.2 使用Spring的事務管理
如果想使用手動提交事務,可以使用該方法。需要注入兩個Bean,最后記得提交事務。
@Autowiredprivate DataSourceTransactionManager dataSourceTransactionManager;@Autowiredprivate TransactionDefinition transactionDefinition;public void testHandleCommitTS(boolean exceptionFlag) { // DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition(); // transactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 開啟事務TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);try {// dosomething
// 提交事務 dataSourceTransactionManager.commit(transactionStatus);} catch (Exception e) {e.printStackTrace();// 回滾事務 dataSourceTransactionManager.rollback(transactionStatus);}}
六、使用SQL語句構建器
MyBatis提供了一個SQL語句構建器,可以讓編寫sql語句更方便。缺點是比原生sql語句,一些功能可能無法實現。
有兩種寫法,SQL語句構建器看個人喜好,我個人比較熟悉原生sql語句,所有挺少使用SQL語句構建器的。
(1) 創建一個對象循環調用方法
new SQL().DELETE_FROM("user_table").WHERE("t_id = #{id}").toString()
(2) 內部類實現?
new SQL() {{DELETE_FROM("user_table");
WHERE("t_id = #{id}"); }}.toString();
需要實現ProviderMethodResolver接口,ProviderMethodResolver接口屬于比較新的api,如果找不到這個接口,更新你的mybatis的版本,或者Mapper的@SelectProvider注解需要加一個?method注解,?@SelectProvider(type = UserBuilder.class,?method?=?"selectUserById")
繼承ProviderMethodResolver接口,Mapper中可以直接指定該類即可,但對應的Mapper的方法名要更Builder的方法名相同?。
Mapper: @SelectProvider(type = UserBuilder.class) public User selectUserById(String id);UserBuilder: public static String selectUserById(final String id)...
dao層代碼:(建議在dao層中的方法加上@see的注解,并指示對應的方法,方便后期的維護)
/*** @see UserBuilder#selectUserById()*/@Results(id ="userResults", value={@Result(property="id", column="t_id"),@Result(property="name", column="t_name"),@Result(property="age", column="t_age"),})@SelectProvider(type = UserBuilder.class)User selectUserById(String id);/*** @see UserBuilder#selectUser(String)*/@ResultMap("userResults")@SelectProvider(type = UserBuilder.class)List<User> selectUser(String name);/*** @see UserBuilder#insertUser()*/@InsertProvider(type = UserBuilder.class)int insertUser(User user);/*** @see UserBuilder#insertUserList(List)*/@InsertProvider(type = UserBuilder.class)int insertUserList(List<User> list);/*** @see UserBuilder#updateUser()*/@UpdateProvider(type = UserBuilder.class)int updateUser(User user);/*** @see UserBuilder#deleteUser()*/@DeleteProvider(type = UserBuilder.class)int deleteUser(String id);
Builder代碼:
public class UserBuilder implements ProviderMethodResolver {private final static String TABLE_NAME = "sys_user";public static String selectUserById() {return new SQL().SELECT("t_id, t_name, t_age").FROM(TABLE_NAME).WHERE("t_id = #{id}").toString();}public static String selectUser(String name) {SQL sql = new SQL().SELECT("t_id, t_name, t_age").FROM(TABLE_NAME);if (name != null && name != "") {sql.WHERE("t_name like CONCAT('%', #{name}, '%')");}return sql.toString();}public static String insertUser() {return new SQL().INSERT_INTO(TABLE_NAME).INTO_COLUMNS("t_id, t_name, t_age").INTO_VALUES("#{id}, #{name}, #{age}").toString();}/*** 使用SQL Builder進行批量插入* 關鍵是sql語句中的values格式書寫和訪問參數* values格式:values (?, ?, ?) , (?, ?, ?) , (?, ?, ?) ...* 訪問參數:MyBatis只能讀取到list參數,所以使用list[i].Filed訪問變量,如 #{list[0].id}*/public static String insertUserList(List<User> list) {SQL sql = new SQL().INSERT_INTO(TABLE_NAME).INTO_COLUMNS("t_id, t_name, t_age");StringBuilder sb = new StringBuilder();for (int i = 0; i < list.size(); i++) {if (i > 0) {sb.append(") , (");}sb.append("#{list[");sb.append(i);sb.append("].id}, ");sb.append("#{list[");sb.append(i);sb.append("].name}, ");sb.append("#{list[");sb.append(i);sb.append("].age}");}sql.INTO_VALUES(sb.toString());return sql.toString();}public static String updateUser() {return new SQL().UPDATE(TABLE_NAME).SET("t_name = #{name}", "t_age = #{age}").WHERE("t_id = #{id}").toString();}public static String deleteUser() {return new SQL().DELETE_FROM(TABLE_NAME).WHERE("t_id = #{id}").toString();
或者? Builder代碼:
public class UserBuilder2 implements ProviderMethodResolver {private final static String TABLE_NAME = "sys_user";public static String selectUserById() {return new SQL() {{SELECT("t_id, t_name, t_age");FROM(TABLE_NAME);WHERE("t_id = #{id}");}}.toString();}public static String selectUser(String name) {return new SQL() {{SELECT("t_id, t_name, t_age");FROM(TABLE_NAME);if (name != null && name != "") {WHERE("t_name like CONCAT('%', #{name}, '%')"); }}}.toString();}public static String insertUser() {return new SQL() {{INSERT_INTO(TABLE_NAME);INTO_COLUMNS("t_id, t_name, t_age");INTO_VALUES("#{id}, #{name}, #{age}");}}.toString();}public static String updateUser(User user) {return new SQL() {{UPDATE(TABLE_NAME);SET("t_name = #{name}", "t_age = #{age}");WHERE("t_id = #{id}");}}.toString();}public static String deleteUser(final String id) {return new SQL() {{DELETE_FROM(TABLE_NAME);WHERE("t_id = #{id}");}}.toString();} }
?七、附屬鏈接
7.1 MyBatis官方源碼?
https://github.com/mybatis/mybatis-3?,源碼的測試包跟全面,更多的使用方法可以參考官方源碼的測試包
7.2 MyBatis官方中文文檔
http://www.mybatis.org/mybatis-3/zh/index.html?,官方中文文檔,建議多閱讀官方的文檔
7.3 我的測試項目地址,可做參考
https://github.com/caizhaokai/spring-boot-demo?,SpringBoot+MyBatis+Redis的demo,有興趣的可以看一看