SpringBoot + MyBatis(註解版),常用的SQL方法
一、新建專案及配置
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開啟事務
五、使用SQL語句構建器
&n