Spring Boot学习记录(三)--整合Mybatis

来源:互联网 发布:网络传播类杂志 编辑:程序博客网 时间:2024/05/29 16:10

Spring Boot学习记录(三)–整合Mybatis

标签(空格分隔): spring-boot


控制器,视图解析器前面两篇都已弄好,这一篇学习持久层框架整合.


1.数据源配置

数据源使用druid,maven引入相关依赖,包括spring-jdbc依赖,mysql依赖

1.转换问题

配置的过程要学会为什么这样配置,而不是只学会了配置.这里我们可以和以前的配置方式对比:

以前版本

    <!--配置数据库连接池Druid-->    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close" init-method="init">        <!-- 数据库基本信息配置 -->        <property name="url" value="${jdbc.url}" />        <property name="username" value="${jdbc.username}" />        <property name="password" value="${jdbc.password}" />        <property name="driverClassName" value="${jdbc.driver}" />        <property name="filters" value="${filters}" />        <!-- 最大并发连接数 -->        <property name="maxActive" value="${maxActive}" />        <!-- 初始化连接数量 -->        <property name="initialSize" value="${initialSize}" />        <!-- 配置获取连接等待超时的时间 -->        <property name="maxWait" value="${maxWait}" />        <!-- 最小空闲连接数 -->        <property name="minIdle" value="${minIdle}" />        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->        <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->        <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />        <property name="validationQuery" value="SELECT 1" />        <property name="testWhileIdle" value="${testWhileIdle}" />        <property name="testOnBorrow" value="${testOnBorrow}" />        <property name="testOnReturn" value="${testOnReturn}" />        <property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements}" />        <!-- 打开removeAbandoned功能 -->        <property name="removeAbandoned" value="${removeAbandoned}" />        <!-- 1800秒,也就是30分钟 -->        <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />        <!-- 关闭abanded连接时输出错误日志 -->        <property name="logAbandoned" value="${logAbandoned}" />    </bean>

以前的版本无非是注入一个com.alibaba.druid.pool.DruidDataSource的bean,那么现在也这样做.
那么问题来了,在SpringBoot中怎么初始配置Bean?

2.springboot中初始化一个Bean

随着问题的提出,就要思考,以前的版本是在xml中使用beans标签,在其里面配置bean,那么纯java代码怎么实现呢?带着问题去搜索很容易找到答案.

答案就是使用@Configuration注解和@Bean,代码如下:当然搜资料过程中你会学习到其他的知识,并尝试使用

import com.alibaba.druid.pool.DruidDataSource;import com.alibaba.druid.support.http.StatViewServlet;import com.alibaba.druid.support.http.WebStatFilter;import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary;import java.sql.SQLException;/** * @author Niu Li * @date 2016/8/12 */@Configurationpublic class DataSourcesConfig {    /**     * druid初始化     * @return     * @throws SQLException     */    @Primary //默认数据源    @Bean(name = "dataSource",destroyMethod = "close")    public DruidDataSource Construction() throws SQLException {        DruidDataSource dataSource = new DruidDataSource();        dataSource.setUrl("jdbc:mysql://localhost:3306/springboot");        dataSource.setUsername("root");        dataSource.setPassword("1111111");        dataSource.setDriverClassName("com.mysql.jdbc.Driver");        //配置最大连接        dataSource.setMaxActive(20);        //配置初始连接        dataSource.setInitialSize(1);        //配置最小连接        dataSource.setMinIdle(1);        //连接等待超时时间        dataSource.setMaxWait(60000);        //间隔多久进行检测,关闭空闲连接        dataSource.setTimeBetweenEvictionRunsMillis(60000);        //一个连接最小生存时间        dataSource.setMinEvictableIdleTimeMillis(300000);        //用来检测是否有效的sql        dataSource.setValidationQuery("select 'x'");        dataSource.setTestWhileIdle(true);        dataSource.setTestOnBorrow(false);        dataSource.setTestOnReturn(false);        //打开PSCache,并指定每个连接的PSCache大小        dataSource.setPoolPreparedStatements(true);        dataSource.setMaxOpenPreparedStatements(20);        //配置sql监控的filter        dataSource.setFilters("stat,wall,log4j");        try {            dataSource.init();        } catch (SQLException e) {            throw new RuntimeException("druid datasource init fail");        }        return dataSource;    }}

配置后可以启动一下,日志中init成功的话即可.
这里写图片描述

到这还有问题,就是druid最大的优势是有一套很完善的监控系统,那么怎么打开这个系统呢?,想想原来的代码:

 <!-- 连接池 启用Web监控统计功能   start-->  <filter>    <filter-name>DruidWebStatFilter</filter-name>    <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>    <init-param>      <param-name>exclusions</param-name>      <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/font/*,/druid/*</param-value>    </init-param>  </filter>  <filter-mapping>    <filter-name>DruidWebStatFilter</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping>  <servlet>    <servlet-name>DruidStatView</servlet-name>    <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>DruidStatView</servlet-name>    <!--访问路径eg:http://localhost:8888/druid/index.html -->    <url-pattern>/druid/*</url-pattern>  </servlet-mapping>

那么问题来了,怎么在springboot中配置servlet和filter?

3.配置servlet,filter等

带着问题接着查资料,能够查到有两种方式配置.

1.使用注解@WebFilter,@WebServlet,@WebListener注解配置,如下:

/** * Druid的StatFilter */@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",        initParams={                @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")// 忽略资源        })public class DruidStatFilter extends WebStatFilter {}

使用这种配置的话,要开启springboot的servlet扫描功能,不然不会生效.
开启的话,在application启动类上加入@ServletComponentScan即可开启自动扫描.

2.基于Bean的配置

springboot提供了
ServletRegistrationBean,FilterRegistrationBean,ServletListenerRegistrationBean三个类来注入servlet,filter,listener,用法如下:

 /**     * druid监控     * @return     */    @Bean    public ServletRegistrationBean druidServlet() {        ServletRegistrationBean reg = new ServletRegistrationBean();        reg.setServlet(new StatViewServlet());        reg.addUrlMappings("/druid/*");        //reg.addInitParameter("allow", "127.0.0.1");        //reg.addInitParameter("deny","");        reg.addInitParameter("loginUsername", "niuli");        reg.addInitParameter("loginPassword", "123456");        return reg;    }    /**     * druid监控过滤     * @return     */    @Bean    public FilterRegistrationBean filterRegistrationBean() {        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();        filterRegistrationBean.setFilter(new WebStatFilter());        filterRegistrationBean.addUrlPatterns("/*");        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");        return filterRegistrationBean;    }

个人比较喜欢第二种,可以把他和数据源配置都放在一起,看起来还清晰很多.

3.测试
启动后直接访问,就能看到数据源配置了
这里写图片描述


2.整合mybatis

maven引入包可以和以前一样,也可以直接引入mybatis-spring-boot-starter整合mybatis主要由以下几点:

  • 原本mybatis的配置xml怎么替代
  • **mapper.xml怎么替代
  • mapper代理接口怎么扫描

1.注入SqlSessionFactory

仿照以前的mybatis整合spring方式,注入相关Bean,下面代码还加入了mybatis插件配置,并且注入事务管理器,方便service使用

/** * mybatis配置类 * @author Niu Li * @date 2016/8/12 */@Configuration@EnableTransactionManagementpublic class MybatisConfig implements TransactionManagementConfigurer{    @Resource(name = "dataSource")    DataSource dataSource;    /**     * 可以通过这个类,详细配置mybatis     * @return     *///    @Bean//    public org.apache.ibatis.session.Configuration mybatisSetting(){//        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();////        return null;//    }    @Bean(name = "sqlSessionFactory")    public SqlSessionFactory sqlSessionFactoryBean() {        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();        bean.setDataSource(dataSource);        bean.setTypeAliasesPackage("cn.mrdear.entity");        //分页插件,插件无非是设置mybatis的拦截器        PageHelper pageHelper = new PageHelper();        Properties properties = new Properties();        properties.setProperty("reasonable", "true");        properties.setProperty("supportMethodsArguments", "true");        properties.setProperty("returnPageInfo", "check");        properties.setProperty("params", "count=countSql");        pageHelper.setProperties(properties);        //添加插件        bean.setPlugins(new Interceptor[]{pageHelper});        //添加XML目录        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();        try {            //设置xml扫描路径            bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));            return bean.getObject();        } catch (Exception e) {            throw new RuntimeException("sqlSessionFactory init fail",e);        }    }    /**     * 用于实际查询的sql工具,传统dao开发形式可以使用这个,基于mapper代理则不需要注入     * @param sqlSessionFactory     * @return     */    @Bean(name = "sqlSessionTemplate")    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {        return new SqlSessionTemplate(sqlSessionFactory);    }    /**     * 事务管理,具体使用在service层加入@Transactional注解     */    @Bean(name = "transactionManager")    @Override    public PlatformTransactionManager annotationDrivenTransactionManager() {        return new DataSourceTransactionManager(dataSource);    }}

2.编写mapper.xml

在resources下建立mapper目录,这里写法和以前一样.路径是上面你自己设置的目录

<?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="cn.mrdear.mapper.UserMapper">    <!--根据id查询用户详情-->    <select id="findById" parameterType="int" resultType="cn.mrdear.entity.User">        SELECT * FROM user WHERE id=#{id}    </select></mapper>

3.编写mapper接口

如果使用mybatis-spring-boot-starter,那么mapper接口扫描就可以使用@Mapper注解替代,mybatis会自动扫描,并把其当成mapper接口来对待.

/** * UserMapper.xml代理 * @author Niu Li * @date 2016/8/13 */@Mapperpublic interface UserMapper {    /**     * 根据id查询用户     * @param id     * @return     */    User findById(int id);}

4.测试

测试直接注入mapper接口,这里使用IDEA的话,可能会报错,IDEA认为UserMapper没有Bean标识,会提示找不到这个Bean,这个不影响代码,这只是IDEA帮你关联springBean的一种提示检测.

    @Resource    private UserMapper userMapper; @RequestMapping(value = "/users",method = RequestMethod.GET)    public @ResponseBody User testUserDao(){        User user = userMapper.findById(1);        return user;    }

这里写图片描述

5.打印sql语句

使用mapper接口代理的话,打印很简单,在application.properties中设置

logging.level.cn.mrdear.mapper = trace

这里写图片描述

至于使用DAO方式,就需要覆盖掉spring-boot默认设置的logger,自定义log.xml文件,然后配置mybatis的log实现器.


到此算是简单配置完毕了,至于其他的相关配置,在后续开发中用到了再补充,这写的纯属为项目做的前言准备


整合项目地址:

https://github.com/nl101531/JavaWEB

4 0
原创粉丝点击