微服务 SpringBoot 2.0(九):整合Mybatis

我是SQL小白,我选Mybatis —— Java面试必修

引言

在第五章我们已经整合了Thymeleaf页面框架,第七章也整合了JdbcTemplate,那今天我们再结合数据库整合Mybatis框架

在接下来的文章中,我会用一个开源的博客源码来做讲解,在学完了这些技能之后也会收获自己一手搭建的博客,是不是很开心呢

动起来

工具

  • SpringBoot版本:2.0.4
  • 开发工具:IDEA 2018
  • Maven:3.3 9
  • JDK:1.8

加入依赖和index界面

首先我们新建一个SpringBoot工程,将index.html放置templates下面,静态资源放在根目录的static下面,如果不懂静态资源加载的朋友,请看我的上一章噢,有对静态资源的加载做了深入的讲解。

当前项目结构如下

5190738-5caee618aca6f3c5.png
目录结构代码

然后加入依赖


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

        <!--如果不知道当前引用mybatis哪个版本,那直接去maven仓库中心查看依赖即可,此依赖已包含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依赖将会提供如下:

  • 自动检测现有的DataSource
  • 将创建并注册SqlSessionFactory的实例,该实例使用SqlSessionFactoryBean将该DataSource作为输入进行传递
  • 将创建并注册从SqlSessionFactory中获取的SqlSessionTemplate的实例。
  • 自动扫描您的mappers,将它们链接到SqlSessionTemplate并将其注册到Spring上下文,以便将它们注入到您的bean中。

就是说,使用了该Starter之后,只需要定义一个DataSource即可(application.yml中可配置),它会自动创建使用该DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。会自动扫描你的Mappers,连接到SqlSessionTemplate,并注册到Spring上下文中。

我们编写一个Controller,然后启动服务查看运行结果

@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,结果如下

5190738-0b1434274e6b977c.png
浏览器访问结果

编写更深层次代码

yml配置数据源
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数据源设置编写

@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);//初始化时建立物理连接的个数
        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;
    }
}

自定义数据源配置
Spring Boot默认使用tomcat-jdbc数据源,如果你想使用其他的数据源,除了在application.yml配置数据源之外,你应该额外添加以下依赖:

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

Spring Boot会智能地选择我们自己配置的这个DataSource实例。

SQL创建

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 '标题',
  CONTENT text DEFAULT NULL COMMENT '内容',
  RELEASE_TITLE varchar(100) DEFAULT NULL COMMENT '发布标题',
  RELEASE_CONTENT text DEFAULT NULL COMMENT '发布内容',
  ABS_CONTENT VARCHAR(255) DEFAULT NULL COMMENT '概要',
  THUMB_IMG  VARCHAR(255)  COMMENT '文章图路径',
  TYPE_CODE varchar(32)  COMMENT '文章分类',
  `AUTHOR_CODE` varchar(32) DEFAULT NULL COMMENT '发帖人CODE',
  `AUTHOR_NAME` varchar(32) DEFAULT NULL COMMENT '发帖人名称',
  `KEYWORDS` varchar(100) DEFAULT NULL COMMENT '关键词(逗号分隔)',
  `VIEWS` int(10) DEFAULT NULL COMMENT '浏览人数',
  `REPLY_NUM` int(10) DEFAULT NULL COMMENT '回复人数',
  GMT_CREATE datetime DEFAULT NULL COMMENT '创建时间',
  GMT_MODIFIED datetime DEFAULT NULL COMMENT '修改时间',
  DATA_STATE int(11) DEFAULT NULL COMMENT '发布状态0-新增、1-已发布、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语句

实体对象

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类
第一种我采用注解方式,同样和往常一样顶一个Mapper接口,然后将SQL语句写在方法上,,简单的语句只需要使用@Insert、@Update、@Delete、@Select这4个注解即可,动态复杂一点的,就需要使用@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 注解允许你指定一个类名和一个方法在执行时来返回运行 允许创建动态 的 SQL。 基于执行的映射语句, MyBatis 会实例化这个类,然后执行由 provider 指定的方法. 该方法可以有选择地接受参数对象属性: type,method。type 属性是类。method 属性是方法名。

最后Controller调用

@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;
    }
}

这样使用浏览器访问就能看到查询的结果了

但有些时候我们更习惯把重点放在xml文件上,接下来我要讲的就是mapper.xml格式,xml格式与普通springMvc中没有区别,我来贴一下详细的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标签中的namespace属性指定对应的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数据访问操作的使用请参考:mybatis官方中文参考文档

分页插件小福利

推荐一个炒鸡好用的分页插件,之前有在工作中使用过,名字叫pagehelper,网上对于该插件的使用有很多讲解,那对SpringBoot自然也是提供了依赖,pom.xml中添加如下依赖

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

然后你只需在查询list之前使用PageHelper.startPage(int pageNum, int pageSize)方法即可。pageNum是第几页,pageSize是每页多少条,然后使用PageInfo实例化,如下

@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")));
        }
        //重点:前置设置
        PageHelper.startPage(page,rows);
        List<BlogArticle> blogArticles = blogArticleXmlMapper.queryArticleList(params);
        //重点:后置封装
        PageInfo<BlogArticle> pageInfo = new PageInfo<>(blogArticles);
        //数据库一共13条件记录
        System.out.println("每页行数:"+pageInfo.getSize());//输出:10
        System.out.println("总页数:" + pageInfo.getPages());//输出:2
        System.out.println("当前页:" + pageInfo.getPageNum());//输出:1
        List<BlogArticle> list = pageInfo.getList();
        //此处若需分页,则返回PageInfo
        return list;
    }

若项目为普通的spring项目,可以在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>

这个分页插件是不是炒鸡简单炒鸡好用啊

总结

到这里 Spring Boot与Mybatis的初步整合就完成了,更多的业务编写就需要展现你搬砖的实力了,那下一章,我们讲解日志体系整合

源码地址:

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


作者有话说:喜欢的话就请移步Java面试必修网,请自备水,更多干、干、干货等着你

猜你喜欢

转载自blog.csdn.net/weixin_33943347/article/details/87425732