微服務(wù) SpringBoot 2.0(九):整合Mybatis

我是SQL小白,我選Mybatis —— 知碼學(xué)院

引言

在第五章我們已經(jīng)整合了Thymeleaf頁(yè)面框架,第七章也整合了JdbcTemplate,那今天我們?cè)俳Y(jié)合數(shù)據(jù)庫(kù)整合Mybatis框架

在接下來的文章中,我會(huì)用一個(gè)開源的博客源碼來做講解,在學(xué)完了這些技能之后也會(huì)收獲自己一手搭建的博客,是不是很開心呢

動(dòng)起來

工具

  • SpringBoot版本:2.0.4
  • 開發(fā)工具:IDEA 2018
  • Maven:3.3 9
  • JDK:1.8

加入依賴和index界面

首先我們新建一個(gè)SpringBoot工程,將index.html放置templates下面,靜態(tài)資源放在根目錄的static下面,如果不懂靜態(tài)資源加載的朋友,請(qǐng)看我的上一章噢,有對(duì)靜態(tài)資源的加載做了深入的講解。

當(dāng)前項(xiàng)目結(jié)構(gòu)如下

目錄結(jié)構(gòu)代碼

然后加入依賴


        <!--thymeleaf模板引擎,無需再引入web模塊-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!--如果不知道當(dāng)前引用mybatis哪個(gè)版本,那直接去maven倉(cāng)庫(kù)中心查看依賴即可,此依賴已包含jdbc依賴-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

mybatis-spring-boot-starter依賴將會(huì)提供如下:

  • 自動(dòng)檢測(cè)現(xiàn)有的DataSource
  • 將創(chuàng)建并注冊(cè)SqlSessionFactory的實(shí)例,該實(shí)例使用SqlSessionFactoryBean將該DataSource作為輸入進(jìn)行傳遞
  • 將創(chuàng)建并注冊(cè)從SqlSessionFactory中獲取的SqlSessionTemplate的實(shí)例。
  • 自動(dòng)掃描您的mappers,將它們鏈接到SqlSessionTemplate并將其注冊(cè)到Spring上下文,以便將它們注入到您的bean中。

就是說,使用了該Starter之后,只需要定義一個(gè)DataSource即可(application.yml中可配置),它會(huì)自動(dòng)創(chuàng)建使用該DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。會(huì)自動(dòng)掃描你的Mappers,連接到SqlSessionTemplate,并注冊(cè)到Spring上下文中。

我們編寫一個(gè)Controller,然后啟動(dòng)服務(wù)查看運(yùn)行結(jié)果

@Controller
@RequestMapping
public class MyBatisCon {

    @RequestMapping("index")
    public ModelAndView index(){
        //這里直接定位到templates下面的文件目錄即可
        ModelAndView modelAndView = new ModelAndView("/themes/skin1/index");
        modelAndView.addObject("title","123321");
        return modelAndView;
    }
}

瀏覽器訪問http://localhost:1000/index,結(jié)果如下

瀏覽器訪問結(jié)果

編寫更深層次代碼

yml配置數(shù)據(jù)源
server:
  port: 1000

spring.datasource:
  url: jdbc:mysql://192.168.2.211:3306/springboot?useUnicode=true&characterEncoding=utf-8
  username: root
  password: 123456
  driver-class-name: com.mysql.jdbc.Driver

Application數(shù)據(jù)源設(shè)置編寫

@SpringBootApplication
public class DemoMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoMybatisApplication.class, args);
    }

    @Autowired
    private Environment env;

    @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);//初始化時(shí)建立物理連接的個(gè)數(shù)
        dataSource.setMaxActive(20);//最大連接池?cái)?shù)量
        dataSource.setMinIdle(0);//最小連接池?cái)?shù)量
        dataSource.setMaxWait(60000);//獲取連接時(shí)最大等待時(shí)間,單位毫秒。
        dataSource.setValidationQuery("SELECT 1");//用來檢測(cè)連接是否有效的sql
        dataSource.setTestOnBorrow(false);//申請(qǐng)連接時(shí)執(zhí)行validationQuery檢測(cè)連接是否有效
        dataSource.setTestWhileIdle(true);//建議配置為true,不影響性能,并且保證安全性。
        dataSource.setPoolPreparedStatements(false);//是否緩存preparedStatement,也就是PSCache
        return dataSource;
    }
}

自定義數(shù)據(jù)源配置
Spring Boot默認(rèn)使用tomcat-jdbc數(shù)據(jù)源,如果你想使用其他的數(shù)據(jù)源,除了在application.yml配置數(shù)據(jù)源之外,你應(yīng)該額外添加以下依賴:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.5</version>
</dependency>

Spring Boot會(huì)智能地選擇我們自己配置的這個(gè)DataSource實(shí)例。

SQL創(chuàng)建

CREATE TABLE `BLOG_ARTICLE` (
  ARTICLE_ID int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  ARTICLE_CODE varchar(32) DEFAULT NULL COMMENT '代碼CODE',
  TITLE varchar(100) DEFAULT NULL COMMENT '標(biāo)題',
  CONTENT text DEFAULT NULL COMMENT '內(nèi)容',
  RELEASE_TITLE varchar(100) DEFAULT NULL COMMENT '發(fā)布標(biāo)題',
  RELEASE_CONTENT text DEFAULT NULL COMMENT '發(fā)布內(nèi)容',
  ABS_CONTENT VARCHAR(255) DEFAULT NULL COMMENT '概要',
  THUMB_IMG  VARCHAR(255)  COMMENT '文章圖路徑',
  TYPE_CODE varchar(32)  COMMENT '文章分類',
  `AUTHOR_CODE` varchar(32) DEFAULT NULL COMMENT '發(fā)帖人CODE',
  `AUTHOR_NAME` varchar(32) DEFAULT NULL COMMENT '發(fā)帖人名稱',
  `KEYWORDS` varchar(100) DEFAULT NULL COMMENT '關(guān)鍵詞(逗號(hào)分隔)',
  `VIEWS` int(10) DEFAULT NULL COMMENT '瀏覽人數(shù)',
  `REPLY_NUM` int(10) DEFAULT NULL COMMENT '回復(fù)人數(shù)',
  GMT_CREATE datetime DEFAULT NULL COMMENT '創(chuàng)建時(shí)間',
  GMT_MODIFIED datetime DEFAULT NULL COMMENT '修改時(shí)間',
  DATA_STATE int(11) DEFAULT NULL COMMENT '發(fā)布狀態(tài)0-新增、1-已發(fā)布、2-已刪除',
  TENANT_CODE varchar(32) DEFAULT NULL COMMENT '租戶ID',
  PRIMARY KEY (`ARTICLE_ID`),
  UNIQUE KEY `UDX_BLOG_ARTICLECODE` (`ARTICLE_CODE`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='文章表';

//insert語句

實(shí)體對(duì)象

public class BlogArticle extends BaseBean{
    //省略getter和setter
    private Long articleId;
    private String articleCode;
    private String title;
    private String content;
    private String releaseTitle;
    private String releaseContent;
    private String absContent;
    private String thumbImg;
    private String typeCode;
    private String authorCode;
    private String authorName;
    private String keywords;
    private Long views;
    private Long replyNum;
}

service

public interface BlogArticleService {
    List<BlogArticle> queryArticleList();
}

@Service
public class BlogArticleServiceImpl implements BlogArticleService {

    @Autowired
    BlogArticleMapper blogArticleMapper;

    @Override
    public List<BlogArticle> queryArticleList(Map<String, Object> params) {
        return blogArticleMapper.queryArticleList(params);
    }
}

mapper類
第一種我采用注解方式,同樣和往常一樣頂一個(gè)Mapper接口,然后將SQL語句寫在方法上,,簡(jiǎn)單的語句只需要使用@Insert、@Update、@Delete、@Select這4個(gè)注解即可,動(dòng)態(tài)復(fù)雜一點(diǎn)的,就需要使用@InsertProvider、@UpdateProvider、@DeleteProvider、@SelectProvider等注解,這些注解是mybatis3中新增的,如下

@Repository
@Mapper
public interface BlogArticleMapper {

    @Insert("insert into blog_article(ARTICLE_CODE, TITLE , CONTENT , ABS_CONTENT , TYPE_CODE , AUTHOR_CODE , AUTHOR_NAME" +
            "KEYWORDS , DATA_STATE , TENANT_CODE) " +
            "values(#{articleCode},#{title},#{content},#{absContent},#{typeCode},#{authorCode},#{authorName},#{keywords}" +
            ",#{dataState}),#{tenantCode})")
    int add(BlogArticle blogArticle);

    @Update("update blog_article set AUTHOR_NAME=#{authorName},title=#{title} where ARTICLE_ID = #{articleId}")
    int update(BlogArticle blogArticle);

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


    @Select("select * from blog_article where ARTICLE_ID = #{articleId}")
    @Results(id = "articleMap", value = {
            @Result(column = "ARTICLE_ID", property = "articleId", javaType = Long.class),
            @Result(property = "AUTHOR_NAME", column = "authorName", javaType = String.class),
            @Result(property = "TITLE", column = "title", javaType = String.class)
    })
    BlogArticle queryArticleById(@Param("articleId") Long articleId);
    
    @SelectProvider(type = ArticleSqlBuilder.class, method = "queryArticleList")
    List<BlogArticle> queryArticleList(Map<String, Object> params);

    class ArticleSqlBuilder {
        public String queryArticleList(final Map<String, Object> params) {
            StringBuffer sql =new StringBuffer();
            sql.append("select * from blog_article where 1 = 1");
            if(params.containsKey("authorName")){
                sql.append(" and authorName like '%").append((String)params.get("authorName")).append("%'");
            }
            if(params.containsKey("releaseTitle")){
                sql.append(" and releaseTitle like '%").append((String)params.get("releaseTitle")).append("%'");
            }
            System.out.println("查詢sql=="+sql.toString());
            return sql.toString();
        }

        //刪除Provider
        public String deleteByids(@Param("ids") final String[] ids){
            StringBuffer sql =new StringBuffer();
            sql.append("DELETE FROM blog_article WHERE articleId 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();
        }

    }
}

這些可選的 SQL 注解允許你指定一個(gè)類名和一個(gè)方法在執(zhí)行時(shí)來返回運(yùn)行 允許創(chuàng)建動(dòng)態(tài) 的 SQL。 基于執(zhí)行的映射語句, MyBatis 會(huì)實(shí)例化這個(gè)類,然后執(zhí)行由 provider 指定的方法. 該方法可以有選擇地接受參數(shù)對(duì)象屬性: type,method。type 屬性是類。method 屬性是方法名。

最后Controller調(diào)用

@Controller
@RequestMapping
public class MyBatisCon {

    @Autowired
    private BlogArticleService blogArticleService;

    @RequestMapping("index")
    public ModelAndView index(){
        Map<String, Object> params = new HashMap<>();
        List<BlogArticle> blogArticles = blogArticleService.queryArticleList(params);
        ModelAndView modelAndView = new ModelAndView("/themes/skin1/index");
        modelAndView.addObject("title","123321");
        modelAndView.addObject("blogArticles",blogArticles);
        return modelAndView;
    }
}

這樣使用瀏覽器訪問就能看到查詢的結(jié)果了

但有些時(shí)候我們更習(xí)慣把重點(diǎn)放在xml文件上,接下來我要講的就是mapper.xml格式,xml格式與普通springMvc中沒有區(qū)別,我來貼一下詳細(xì)的mapper代碼

XML寫法

dao層寫法
新建BlogArticleXmlMapper 接口
@Mapper
public interface BlogArticleXmlMapper {
    int add(BlogArticle blogArticle);

    int update(BlogArticle blogArticle);

    int deleteByIds(String[] ids);

    BlogArticle queryArticleById(Long articleId);

    List<BlogArticle> queryArticleList(Map<String, Object> params);

}
修改application.yml文件
#指定bean所在包
mybatis.type-aliases-package: com.fox.demomybaits.bean
#指定映射文件,在src/main/resources下新建mapper文件夾
mybatis.mapperLocations: classpath:mapper/*.xml
添加BlogArticleXmlMapper.xml的映射文件

mapper.xml標(biāo)簽中的namespace屬性指定對(duì)應(yīng)的dao映射,這里指向BlogArticleXmlMapper

<?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.fox.demomybatis.dao.BlogArticleXmlMapper">
    <resultMap id="baseResultMap" type="com.fox.demomybatis.bean.BlogArticle">
        <id column="article_id" property="articleId" jdbcType="BIGINT"  />
        <result column="article_code" property="articleCode" jdbcType="VARCHAR"/>
        <result column="title" property="title" jdbcType="VARCHAR"/>
        <result column="content" property="content" jdbcType="LONGVARCHAR"/>
        <result column="release_title" property="releaseTitle" jdbcType="VARCHAR"/>
        <result column="release_content" property="releaseContent" jdbcType="LONGVARCHAR"/>
        <result column="abs_content" property="absContent" jdbcType="VARCHAR"/>
        <result column="thumb_img" property="thumbImg" jdbcType="VARCHAR"/>
        <result column="type_code" property="typeCode" jdbcType="VARCHAR"/>
        <result column="author_code" property="authorCode" jdbcType="VARCHAR"/>
        <result column="author_name" property="authorName" jdbcType="VARCHAR"/>
        <result column="keywords" property="keywords" jdbcType="BIGINT"/>
        <result column="views" property="views" jdbcType="BIGINT"/>
        <result column="gmt_create" property="gmtCreate" jdbcType="TIMESTAMP"/>
        <result column="gmt_modified" property="gmtModified" jdbcType="TIMESTAMP"/>
        <result column="data_state" property="dataState" jdbcType="INTEGER"/>
        <result column="tenant_code" property="tenantCode" jdbcType="VARCHAR"/>
    </resultMap>



    <sql id="baseColumnList" >
        article_id, article_code, title,content, release_title,release_content,abs_content,thumb_img,type_code,author_code
        ,author_name,keywords,views,gmt_create,gmt_modified,data_state,tenant_code
    </sql>

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

        </where>
    </select>

    <select id="queryArticleById"  resultMap="baseResultMap" parameterType="java.lang.Long">
        SELECT
        <include refid="baseColumnList" />
        FROM blog_article
        WHERE article_id = #{articleId}
    </select>

    <insert id="add" parameterType="com.fox.demomybatis.bean.BlogArticle" >
        INSERT INTO blog_article (authorName, title) VALUES (#{authorName}, #{title})
    </insert>

    <update id="update" parameterType="com.fox.demomybatis.bean.BlogArticle" >
        UPDATE blog_article SET authorName = #{authorName},title = #{title} WHERE article_id = #{articleId}
    </update>

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

更多mybatis數(shù)據(jù)訪問操作的使用請(qǐng)參考:mybatis官方中文參考文檔

分頁(yè)插件小福利

推薦一個(gè)炒雞好用的分頁(yè)插件,之前有在工作中使用過,名字叫pagehelper,網(wǎng)上對(duì)于該插件的使用有很多講解,那對(duì)SpringBoot自然也是提供了依賴,pom.xml中添加如下依賴

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.3</version>
</dependency>
#pagehelper分頁(yè)插件配置,yml配置文件中使用
pagehelper: 
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql

然后你只需在查詢list之前使用PageHelper.startPage(int pageNum, int pageSize)方法即可。pageNum是第幾頁(yè),pageSize是每頁(yè)多少條,然后使用PageInfo實(shí)例化,如下

@Override
    public List<BlogArticle> queryArticleList(Map<String, Object> params) {
        Integer page = 1;
        if(params.containsKey("page")){
            page = Integer.valueOf(String.valueOf(params.get("page")));
        }
        Integer rows = 10;
        if(params.containsKey("rows")){
            rows = Integer.valueOf(String.valueOf(params.get("rows")));
        }
        //重點(diǎn):前置設(shè)置
        PageHelper.startPage(page,rows);
        List<BlogArticle> blogArticles = blogArticleXmlMapper.queryArticleList(params);
        //重點(diǎn):后置封裝
        PageInfo<BlogArticle> pageInfo = new PageInfo<>(blogArticles);
        //數(shù)據(jù)庫(kù)一共13條件記錄
        System.out.println("每頁(yè)行數(shù):"+pageInfo.getSize());//輸出:10
        System.out.println("總頁(yè)數(shù):" + pageInfo.getPages());//輸出:2
        System.out.println("當(dāng)前頁(yè):" + pageInfo.getPageNum());//輸出:1
        List<BlogArticle> list = pageInfo.getList();
        //此處若需分頁(yè),則返回PageInfo
        return list;
    }

若項(xiàng)目為普通的spring項(xiàng)目,可以在spring.xml中如下配置

//xml配置使用
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
          <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <value>
                            helperDialect=mysql
                            reasonable=false
                            supportMethodsArguments=true
                            params=count=countSql
                            autoRuntimeDialect=true
                            count=countSql
                        </value>
                    </property>
                </bean>
            </array>
              
        </property> 
</bean>

這個(gè)分頁(yè)插件是不是炒雞簡(jiǎn)單炒雞好用啊

總結(jié)

到這里 Spring Boot與Mybatis的初步整合就完成了,更多的業(yè)務(wù)編寫就需要展現(xiàn)你搬磚的實(shí)力了,那下一章,我們講解日志體系整合

源碼地址:

https://gitee.com/rjj1/SpringBootNote/tree/master/demo-mybatis


作者有話說:喜歡的話就請(qǐng)移步知碼學(xué)院,請(qǐng)自備水,更多干、干、干貨等著你

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容