Spring Boot乾貨系列:(九)資料儲存篇-SQL關係型資料庫之MyBatis的使用 | 掘金技術徵文

嘟嘟MD發表於2017-04-23

原本地址:Spring Boot乾貨系列:(九)資料儲存篇-SQL關係型資料庫之MyBatis的使用
部落格地址:tengj.top/

前言

上篇我們介紹了Spring Boot對傳統JdbcTemplate的整合,這次換一下,介紹下Spring Boot中如何整合MyBatis。這裡分別介紹註解方式以及XML方式的整合。喜歡哪種方式自己選擇。

正文

專案框架還是跟上一篇一樣使用Spring Boot的ace後端模板,你可以基於它來跟著博主一起來調整程式碼,如果沒看過上一篇,那就下載本篇原始碼研究吧。

跟上篇一樣先新增基礎的依賴和資料來源。

新增依賴

這裡需要新增mybatis-spring-boot-starter依賴跟mysql依賴

 <!--最新版本,匹配spring Boot1.5 or higher-->
 <dependency>
     <groupId>org.mybatis.spring.boot</groupId>
     <artifactId>mybatis-spring-boot-starter</artifactId>
     <version>1.3.0</version>
 </dependency>

<dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
 </dependency>複製程式碼

這裡不引入spring-boot-starter-jdbc依賴,是由於mybatis-spring-boot-starter中已經包含了此依賴。

博主開始整理的時候發現mybatis-spring-boot-starter有新版本了,這裡就整合最新的,匹配Spring Boot1.5版本。

Spring Boot乾貨系列:(九)資料儲存篇-SQL關係型資料庫之MyBatis的使用 | 掘金技術徵文

MyBatis-Spring-Boot-Starter依賴將會提供如下:

  • 自動檢測現有的DataSource
  • 將建立並註冊SqlSessionFactory的例項,該例項使用SqlSessionFactoryBean將該DataSource作為輸入進行傳遞
  • 將建立並註冊從SqlSessionFactory中獲取的SqlSessionTemplate的例項。
  • 自動掃描您的mappers,將它們連結到SqlSessionTemplate並將其註冊到Spring上下文,以便將它們注入到您的bean中。

就是說,使用了該Starter之後,只需要定義一個DataSource即可(application.properties中可配置),它會自動建立使用該DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。會自動掃描你的Mappers,連線到SqlSessionTemplate,並註冊到Spring上下文中。

資料來源配置

在src/main/resources/application.properties中配置資料來源資訊。

 spring.datasource.url = jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8
 spring.datasource.username = root
 spring.datasource.password = root
 spring.datasource.driver-class-name = com.mysql.jdbc.Driver複製程式碼

自定義資料來源

Spring Boot預設使用tomcat-jdbc資料來源,如果你想使用其他的資料來源,比如這裡使用了阿里巴巴的資料池管理,除了在application.properties配置資料來源之外,你應該額外新增以下依賴:

 <dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>druid</artifactId>
     <version>1.0.19</version>
 </dependency>複製程式碼

修改Application.java

 @SpringBootApplication
 public class Application {
    public static void main(String[] args) {
         SpringApplication.run(Application.class, args);
     }
    @Autowired
     private Environment env;
    //destroy-method="close"的作用是當資料庫連線不使用的時候,就把該連線重新放到資料池中,方便下次使用呼叫.
     @Bean(destroyMethod =  "close")
     public DataSource dataSource() {
         DruidDataSource dataSource = new DruidDataSource();
         dataSource.setUrl(env.getProperty("spring.datasource.url"));
         dataSource.setUsername(env.getProperty("spring.datasource.username"));//使用者名稱
         dataSource.setPassword(env.getProperty("spring.datasource.password"));//密碼
         dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
         dataSource.setInitialSize(2);//初始化時建立物理連線的個數
         dataSource.setMaxActive(20);//最大連線池數量
         dataSource.setMinIdle(0);//最小連線池數量
         dataSource.setMaxWait(60000);//獲取連線時最大等待時間,單位毫秒。
         dataSource.setValidationQuery("SELECT 1");//用來檢測連線是否有效的sql
         dataSource.setTestOnBorrow(false);//申請連線時執行validationQuery檢測連線是否有效
         dataSource.setTestWhileIdle(true);//建議配置為true,不影響效能,並且保證安全性。
         dataSource.setPoolPreparedStatements(false);//是否快取preparedStatement,也就是PSCache
         return dataSource;
     }
 }複製程式碼

ok這樣就算自己配置了一個DataSource,Spring Boot會智慧地選擇我們自己配置的這個DataSource例項。

指令碼初始化

 CREATE DATABASE /*!32312 IF NOT EXISTS*/`spring` /*!40100 DEFAULT CHARACTER SET utf8 */;
 USE `spring`;
 DROP TABLE IF EXISTS `learn_resource`;

CREATE TABLE `learn_resource` (
   `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
   `author` varchar(20) DEFAULT NULL COMMENT '作者',
   `title` varchar(100) DEFAULT NULL COMMENT '描述',
   `url` varchar(100) DEFAULT NULL COMMENT '地址連結',
   PRIMARY KEY (`id`)
 ) ENGINE=MyISAM AUTO_INCREMENT=1029 DEFAULT CHARSET=utf8;

insert into `learn_resource`(`id`,`author`,`title`,`url`) values (999,'官方SpriongBoot例子','官方SpriongBoot例子','https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples');
 insert into `learn_resource`(`id`,`author`,`title`,`url`) values (1000,'龍果學院','Spring Boot 教程系列學習','http://www.roncoo.com/article/detail/124661');
 insert into `learn_resource`(`id`,`author`,`title`,`url`) values (1001,'嘟嘟MD獨立部落格','Spring Boot乾貨系列','http://tengj.top/');
 insert into `learn_resource`(`id`,`author`,`title`,`url`) values (1002,'後端程式設計嘟','Spring Boot視訊教程','http://www.toutiao.com/m1559096720023553/');複製程式碼

註解方式跟XML配置方式共同的模組編碼

不管是註解方式還是XML配置的方式,以下程式碼模組都是一樣的

實體物件

 public class LearnResouce {
     private Long id;
     private String author;
     private String title;
     private String url;
     // SET和GET方法
 }複製程式碼

Controller層

 /** 教程頁面
  * Created by tengj on 2017/3/13.
  */
 @Controller
 @RequestMapping("/learn")
 public class LearnController {
     @Autowired
     private LearnService learnService;
     private Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping("")
     public String learn(){
         return "learn-resource";
     }

    @RequestMapping(value = "/queryLeanList",method = RequestMethod.POST,produces="application/json;charset=UTF-8")
     @ResponseBody
     public void queryLearnList(HttpServletRequest request ,HttpServletResponse response){
         String page = request.getParameter("page"); // 取得當前頁數,注意這是jqgrid自身的引數
         String rows = request.getParameter("rows"); // 取得每頁顯示行數,,注意這是jqgrid自身的引數
         String author = request.getParameter("author");
         String title = request.getParameter("title");
         Map<String,Object> params = new HashMap<String,Object>();
         params.put("page", page);
         params.put("rows", rows);
         params.put("author", author);
         params.put("title", title);
         List<LearnResouce> learnList=learnService.queryLearnResouceList(params);
         PageInfo<LearnResouce> pageInfo =new PageInfo<LearnResouce>(learnList);
         JSONObject jo=new JSONObject();
         jo.put("rows", learnList);
         jo.put("total", pageInfo.getPages());//總頁數
         jo.put("records",pageInfo.getTotal());//查詢出的總記錄數
         ServletUtil.createSuccessResponse(200, jo, response);
     }
     /**
      * 新添教程
      * @param request
      * @param response
      */
     @RequestMapping(value = "/add",method = RequestMethod.POST)
     public void addLearn(HttpServletRequest request , HttpServletResponse response){
         JSONObject result=new JSONObject();
         String author = request.getParameter("author");
         String title = request.getParameter("title");
         String url = request.getParameter("url");
         if(StringUtil.isNull(author)){
             result.put("message","作者不能為空!");
             result.put("flag",false);
             ServletUtil.createSuccessResponse(200, result, response);
             return;
         }
         if(StringUtil.isNull(title)){
             result.put("message","教程名稱不能為空!");
             result.put("flag",false);
             ServletUtil.createSuccessResponse(200, result, response);
             return;
         }
         if(StringUtil.isNull(url)){
             result.put("message","地址不能為空!");
             result.put("flag",false);
             ServletUtil.createSuccessResponse(200, result, response);
             return;
         }
         LearnResouce learnResouce = new LearnResouce();
         learnResouce.setAuthor(author);
         learnResouce.setTitle(title);
         learnResouce.setUrl(url);
         int index=learnService.add(learnResouce);
         if(index>0){
             result.put("message","教程資訊新增成功!");
             result.put("flag",true);
         }else{
             result.put("message","教程資訊新增失敗!");
             result.put("flag",false);
         }
         ServletUtil.createSuccessResponse(200, result, response);
     }
     /**
      * 修改教程
      * @param request
      * @param response
      */
     @RequestMapping(value = "/update",method = RequestMethod.POST)
     public void updateLearn(HttpServletRequest request , HttpServletResponse response){
         JSONObject result=new JSONObject();
         String id = request.getParameter("id");
         LearnResouce learnResouce=learnService.queryLearnResouceById(Long.valueOf(id));
         String author = request.getParameter("author");
         String title = request.getParameter("title");
         String url = request.getParameter("url");
         if(StringUtil.isNull(author)){
             result.put("message","作者不能為空!");
             result.put("flag",false);
             ServletUtil.createSuccessResponse(200, result, response);
             return;
         }
         if(StringUtil.isNull(title)){
             result.put("message","教程名稱不能為空!");
             result.put("flag",false);
             ServletUtil.createSuccessResponse(200, result, response);
             return;
         }
         if(StringUtil.isNull(url)){
             result.put("message","地址不能為空!");
             result.put("flag",false);
             ServletUtil.createSuccessResponse(200, result, response);
             return;
         }
         learnResouce.setAuthor(author);
         learnResouce.setTitle(title);
         learnResouce.setUrl(url);
         int index=learnService.update(learnResouce);
         System.out.println("修改結果="+index);
         if(index>0){
             result.put("message","教程資訊修改成功!");
             result.put("flag",true);
         }else{
             result.put("message","教程資訊修改失敗!");
             result.put("flag",false);
         }
         ServletUtil.createSuccessResponse(200, result, response);
     }
     /**
      * 刪除教程
      * @param request
      * @param response
      */
     @RequestMapping(value="/delete",method = RequestMethod.POST)
     @ResponseBody
     public void deleteUser(HttpServletRequest request ,HttpServletResponse response){
         String ids = request.getParameter("ids");
         System.out.println("ids==="+ids);
         JSONObject result = new JSONObject();
         //刪除操作
         int index = learnService.deleteByIds(ids.split(","));
         if(index>0){
             result.put("message","教程資訊刪除成功!");
             result.put("flag",true);
         }else{
             result.put("message","教程資訊刪除失敗!");
             result.put("flag",false);
         }
         ServletUtil.createSuccessResponse(200, result, response);
     }
 }複製程式碼

Service層

 package com.dudu.service;
 public interface LearnService {
     int add(LearnResouce learnResouce);
     int update(LearnResouce learnResouce);
     int deleteByIds(String[] ids);
     LearnResouce queryLearnResouceById(Long learnResouce);
     List<LearnResouce> queryLearnResouceList(Map<String, Object> params);
 }複製程式碼

實現類

 package com.dudu.service.impl;

/**
  * Created by tengj on 2017/4/7.
  */
 @Service
 public class LearnServiceImpl implements LearnService {

    @Autowired
     LearnMapper learnMapper;
     @Override
     public int add(LearnResouce learnResouce) {
         return this.learnMapper.add(learnResouce);
     }

    @Override
     public int update(LearnResouce learnResouce) {
         return this.learnMapper.update(learnResouce);
     }

    @Override
     public int deleteByIds(String[] ids) {
         return this.learnMapper.deleteByIds(ids);
     }

    @Override
     public LearnResouce queryLearnResouceById(Long id) {
         return this.learnMapper.queryLearnResouceById(id);
     }

    @Override
     public List<LearnResouce> queryLearnResouceList(Map<String,Object> params) {
         PageHelper.startPage(Integer.parseInt(params.get("page").toString()), Integer.parseInt(params.get("rows").toString()));
         return this.learnMapper.queryLearnResouceList(params);
     }
 }複製程式碼

Mybatis整合

接下來,我們分別來介紹下註解方式以及XML配置方式。

方案一:註解方式

Mybatis註解的方式好簡單,只要定義一個dao介面,然後sql語句通過註解寫在介面方法上。最後給這個介面新增@Mapper註解或者在啟動類上新增@MapperScan("com.dudu.dao")註解都行。

如下:

 package com.dudu.dao;
 /**
  * Created by tengj on 2017/4/22.
  * Component註解不新增也沒事,只是不加service那邊引入LearnMapper會有錯誤提示,但不影響
  */
 @Component
 @Mapper
 public interface LearnMapper {
     @Insert("insert into learn_resource(author, title,url) values(#{author},#{title},#{url})")
     int add(LearnResouce learnResouce);

    @Update("update learn_resource set author=#{author},title=#{title},url=#{url} where id = #{id}")
     int update(LearnResouce learnResouce);

    @DeleteProvider(type = LearnSqlBuilder.class, method = "deleteByids")
     int deleteByIds(@Param("ids") String[] ids);

    @Select("select * from learn_resource where id = #{id}")
     @Results(id = "learnMap", value = {
             @Result(column = "id", property = "id", javaType = Long.class),
             @Result(property = "author", column = "author", javaType = String.class),
             @Result(property = "title", column = "title", javaType = String.class)
     })
     LearnResouce queryLearnResouceById(@Param("id") Long id);

    @SelectProvider(type = LearnSqlBuilder.class, method = "queryLearnResouceByParams")
     List<LearnResouce> queryLearnResouceList(Map<String, Object> params);

    class LearnSqlBuilder {
         public String queryLearnResouceByParams(final Map<String, Object> params) {
             StringBuffer sql =new StringBuffer();
             sql.append("select * from learn_resource where 1=1");
             if(!StringUtil.isNull((String)params.get("author"))){
                 sql.append(" and author like '%").append((String)params.get("author")).append("%'");
             }
             if(!StringUtil.isNull((String)params.get("title"))){
                 sql.append(" and title like '%").append((String)params.get("title")).append("%'");
             }
             System.out.println("查詢sql=="+sql.toString());
             return sql.toString();
         }

        //刪除的方法
         public String deleteByids(@Param("ids") final String[] ids){
             StringBuffer sql =new StringBuffer();
             sql.append("DELETE FROM learn_resource WHERE id in(");
             for (int i=0;i<ids.length;i++){
                 if(i==ids.length-1){
                     sql.append(ids[i]);
                 }else{
                     sql.append(ids[i]).append(",");
                 }
             }
             sql.append(")");
             return sql.toString();
         }
     }
 }複製程式碼

需要注意的是,簡單的語句只需要使用@Insert、@Update、@Delete、@Select這4個註解即可,但是有些複雜點需要動態SQL語句,就比如上面方法中根據查詢條件是否有值來動態新增sql的,就需要使用@InsertProvider、@UpdateProvider、@DeleteProvider、@SelectProvider等註解。

這些可選的 SQL 註解允許你指定一個類名和一個方法在執行時來返回執行 允許建立動態 的 SQL。 基於執行的對映語句, MyBatis 會例項化這個類,然後執行由 provider 指定的方法. 該方法可以有選擇地接受引數物件.(In MyBatis 3.4 or later, it's allow multiple parameters) 屬性: type,method。type 屬性是類。method 屬性是方法名。 注意: 這節之後是對 類的 討論,它可以幫助你以乾淨,容於閱讀 的方式來構建動態 SQL。

方案二:XML配置方式

xml配置方式保持對映檔案的老傳統,優化主要體現在不需要實現dao的是實現層,系統會自動根據方法名在對映檔案中找對應的sql,具體操作如下:

編寫Dao層的程式碼
新建LearnMapper介面,無需具體實現類。

 package com.dudu.dao;
 @Mapper
 public interface LearnMapper {
     int add(LearnResouce learnResouce);
     int update(LearnResouce learnResouce);
     int deleteByIds(String[] ids);
     LearnResouce queryLearnResouceById(Long id);
     public List<LearnResouce> queryLearnResouceList(Map<String, Object> params);
 }複製程式碼

修改application.properties 配置檔案

 #指定bean所在包
 mybatis.type-aliases-package=com.dudu.domain
 #指定對映檔案
 mybatis.mapperLocations=classpath:mapper/*.xml複製程式碼

新增LearnMapper的對映檔案
在src/main/resources目錄下新建一個mapper目錄,在mapper目錄下新建LearnMapper.xml檔案。

通過mapper標籤中的namespace屬性指定對應的dao對映,這裡指向LearnMapper。

 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 <mapper namespace="com.dudu.dao.LearnMapper">
   <resultMap id="baseResultMap" type="com.dudu.domain.LearnResouce">
     <id column="id" property="id" jdbcType="BIGINT"  />
     <result column="author" property="author" jdbcType="VARCHAR"/>
     <result column="title" property="title" jdbcType="VARCHAR"/>
     <result column="url" property="url" jdbcType="VARCHAR"/>
   </resultMap>

  <sql id="baseColumnList" >
     id, author, title,url
   </sql>

  <select id="queryLearnResouceList" resultMap="baseResultMap" parameterType="java.util.HashMap">
     select
     <include refid="baseColumnList" />
     from learn_resource
     <where>
       1 = 1
       <if test="author!= null and author !=''">
         AND author like CONCAT(CONCAT('%',#{author,jdbcType=VARCHAR}),'%')
       </if>
       <if test="title != null and title !=''">
         AND title like  CONCAT(CONCAT('%',#{title,jdbcType=VARCHAR}),'%')
       </if>

    </where>
   </select>

  <select id="queryLearnResouceById"  resultMap="baseResultMap" parameterType="java.lang.Long">
     SELECT
     <include refid="baseColumnList" />
     FROM learn_resource
     WHERE id = #{id}
   </select>

  <insert id="add" parameterType="com.dudu.domain.LearnResouce" >
     INSERT INTO learn_resource (author, title,url) VALUES (#{author}, #{title}, #{url})
   </insert>

  <update id="update" parameterType="com.dudu.domain.LearnResouce" >
     UPDATE learn_resource SET author = #{author},title = #{title},url = #{url} WHERE id = #{id}
   </update>

  <delete id="deleteByIds" parameterType="java.lang.String" >
     DELETE FROM learn_resource WHERE id in
     <foreach item="idItem" collection="array" open="(" separator="," close=")">
       #{idItem}
     </foreach>
   </delete>
 </mapper>複製程式碼

更多mybatis資料訪問操作的使用請參考:mybatis官方中文參考文件

分頁外掛

上面我有使用到物理分頁外掛pagehelper,用法還算簡單,配置如下
pom.xml中新增依賴

 <dependency>
     <groupId>com.github.pagehelper</groupId>
     <artifactId>pagehelper-spring-boot-starter</artifactId>
     <version>1.1.0</version>
 </dependency>複製程式碼

然後你只需在查詢list之前使用PageHelper.startPage(int pageNum, int pageSize)方法即可。pageNum是第幾頁,pageSize是每頁多少條。

 @Override
     public List<LearnResouce> queryLearnResouceList(Map<String,Object> params) {
         PageHelper.startPage(Integer.parseInt(params.get("page").toString()), Integer.parseInt(params.get("rows").toString()));
         return this.learnMapper.queryLearnResouceList(params);
     }複製程式碼

分頁外掛PageHelper專案地址: github.com/pagehelper/…

最終專案效果如下,增刪改查分頁一個都不少:

Spring Boot乾貨系列:(九)資料儲存篇-SQL關係型資料庫之MyBatis的使用 | 掘金技術徵文

總結

到此為止,Spring Boot與Mybatis的初步整合就完成了,專案不僅整合了bootstrap模板框架,還包含了登入、攔截器、日誌框架logback等前面介紹的功能。麻雀雖小,五臟俱全。

想要檢視更多Spring Boot乾貨教程,可前往:Spring Boot乾貨系列總綱

原始碼下載

( ̄︶ ̄)↗[相關示例完整程式碼]

  • chapter9==》Spring Boot乾貨系列:(九)資料儲存篇-SQL關係型資料庫之MyBatis-註解方式
  • chapter9-2==》Spring Boot乾貨系列:(九)資料儲存篇-SQL關係型資料庫之MyBatis-XML配置方式

想要ace模板原始碼的話,在博主公眾號(javaLearn)回覆關鍵字:ace

一直覺得自己寫的不是技術,而是情懷,一篇篇文章是自己這一路走來的痕跡。靠專業技能的成功是最具可複製性的,希望我的這條路能讓你少走彎路,希望我能幫你抹去知識的蒙塵,希望我能幫你理清知識的脈絡,希望未來技術之巔上有你也有我!

掘金技術徵文

掘金技術徵文第三期:聊聊你的最佳實踐

相關文章