<dependency>
<groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.1</version> </dependency>
application.properties文件下配置(使用的是MySql數據庫)html
# 注:個人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 註解便可(通常使用該註解便可,它是一個組合註解)java
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
以後dao層的接口文件放在Application.java 能掃描到的位置便可,dao層文件使用@Mapper註解mysql
@Mapper public interface UserDao { /** * 測試鏈接 */ @Select("select 1 from dual") int testSqlConnent(); }
測試接口能返回數據即代表鏈接成功git
(1) 能夠傳入一個JavaBeangithub
(2) 能夠傳入一個Mapspring
(3) 能夠傳入多個參數,需使用@Param("ParamName") 修飾參數sql
接口方法返回值可使用 void 或 int,int返回值表明影響行數數據庫
查詢語句中,如何名稱不一致,如何處理數據庫字段映射到Java中的Bean呢?api
(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);
我在測試的時候,爲了方便,給JavaBean 添加了一個帶參數的構造器。後面在測試resultMap 的映射時,發現把映射關係@Results 註釋掉,返回的bean 仍是有數據的;更改查詢字段順序時,出現 java.lang.NumberFormatException: For input string: "hello"的異常。通過測試,發現是bean 的構造器問題。並有如下整理:
(1) bean 只有一個有參的構造方法,MyBatis 調用該構造器(參數按順序),此時@results 註解無效。並有查詢結果個數跟構造器不一致時,報異常。
(2) bean 有多個構造方法,且沒有 無參構造器,MyBatis 調用跟查詢字段數量相同的構造器;若沒有數量相同的構造器,則報異常。
(3) bean 有多個構造方法,且有 無參構造器, MyBatis 調用無參數造器。
(4) 綜上,通常狀況下,bean 不要定義有參的構造器;若須要,請再定義一個無參的構造器。
/** * 測試鏈接 */ @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();
註解版下,使用動態SQL須要將sql語句包含在script標籤裏
<script></script>
經過判斷動態拼接sql語句,通常用於判斷查詢條件
<if test=''>...</if>
根據條件選擇
<choose> <when test=''> ... </when> <when test=''> ... </when> <otherwise> ... </otherwise> </choose>
通常跟if 或choose 聯合使用,這些標籤或去掉多餘的 關鍵字 或 符號。如
<where> <if test="id != null "> and t_id = #{id} </if> </where>
若id爲null,則沒有條件語句;若id不爲 null,則條件語句爲 where t_id = ?
<where> ... </where> <set> ... </set>
綁定一個值,可應用到查詢語句中
<bind name="" value="" />
循環,可對傳入和集合進行遍歷。通常用於批量更新和查詢語句的 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")
/** * 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);
首先看@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);
測試結果,能夠看到只調用一個方法查詢,相關對一查詢和對多查詢也會一併查詢出來
// 測試類代碼 @Test public 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]]
@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..
}
若是想使用手動提交事務,可使用該方法。須要注入兩個Bean,最後記得提交事務。
@Autowired private DataSourceTransactionManager dataSourceTransactionManager; @Autowired private 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); } }
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(); } }
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,有興趣的能夠看一看