美文网首页spring boot相关SpringBoot之路spring
spring boot 1.4 整合 mybatis druid

spring boot 1.4 整合 mybatis druid

作者: liangchong998 | 来源:发表于2016-08-19 13:35 被阅读8005次

    spring boot 1.4 整合 mybatis,使用 druid 数据库连接池

    项目结构目录 ## 结构

    maven 引入 spring boot 开发依赖

      <parent>  
        <groupId>org.springframework.boot</groupId> 
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
      </parent>
      <properties>  
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <dependencies>  
        <dependency>
         <groupId>org.springframework.boot</groupId>   
         <artifactId>spring-boot-starter-thymeleaf</artifactId>    
        </dependency>  
        <dependency>    
          <groupId>org.springframework.boot</groupId>    
          <artifactId>spring-boot-starter-test</artifactId>     
        </dependency>  
        <!--    devtools可以实现页面热部署(即页面修改后会立即生效,这个可以直接在application.properties文件中配置spring.thymeleaf.cache=false来实现),   
         实现类文件热部署(类文件修改后不会立即生效),实现对属性文件的热部署。    即devtools会监听classpath下的文件变动,并且会立即重启应用(发生在保存时机),注意:因为其采用的虚拟机机制,该项重启是很快的  -->  
        <dependency>    
          <groupId>org.springframework.boot</groupId>    
          <artifactId>spring-boot-devtools</artifactId>    
          <optional>true</optional>  
        </dependency>  
        <!-- mybatis -->  
        <dependency>    
          <groupId>org.mybatis.spring.boot</groupId>    
          <artifactId>mybatis-spring-boot-starter</artifactId>    
          <version>1.1.1</version>  
        </dependency>  
        <!-- mybatis 分页插件 -->  
        <dependency>    
          <groupId>com.github.pagehelper</groupId>    
          <artifactId>pagehelper</artifactId>    
          <version>4.1.6</version>  
        </dependency>  
        <!--mysql-->  
        <dependency>    
          <groupId>mysql</groupId>    
          <artifactId>mysql-connector-java</artifactId>  
        </dependency>  
        <!--druid-->  
        <dependency>    
          <groupId>com.alibaba</groupId>    
          <artifactId>druid</artifactId>    
          <version>1.0.20</version>  
        </dependency>
      </dependencies>
    
      <build>  
        <finalName>spring-boot-druid</finalName>  
        <plugins>    
          <plugin>      
            <groupId>org.springframework.boot</groupId>      
            <artifactId>spring-boot-maven-plugin</artifactId>    
          </plugin>  
        </plugins>  
        <resources>    
          <resource>      
            <directory>src/main/java</directory>      
            <includes>        
              <!-- 我习惯将mybatis的配置xml放在java目录下 -->        
              <include>**/*.xml</include>      
            </includes>      
            <filtering>true</filtering>    
          </resource>    
          <resource>      
            <directory>src/main/resources</directory>      
            <includes>        
              <include>**/*</include>      
            </includes>      
            <filtering>true</filtering>    
          </resource>  
        </resources>
      </build>
    

    application.properties

    数据库连接信息与 druid 的连接池配置信息
    thymeleaf 模板的配置

    #数据库配置
    spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.datasource.url=jdbc:mysql://192.168.1.28:3306/chidu
    spring.datasource.username=root
    spring.datasource.password=1qaz2WSX
    # 下面为连接池的补充设置,应用到上面所有数据源中# 初始化大小,最小,最大
    spring.datasource.initialSize=5
    spring.datasource.minIdle=5
    spring.datasource.maxActive=20
    # 配置获取连接等待超时的时间
    spring.datasource.maxWait=60000
    # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    spring.datasource.timeBetweenEvictionRunsMillis=60000
    # 配置一个连接在池中最小生存的时间,单位是毫秒
    spring.datasource.minEvictableIdleTimeMillis=300000
    spring.datasource.validationQuery=SELECT 1 FROM DUAL
    spring.datasource.testWhileIdle=true
    spring.datasource.testOnBorrow=false
    spring.datasource.testOnReturn=false
    # 打开PSCache,并且指定每个连接上PSCache的大小
    spring.datasource.poolPreparedStatements=true
    spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    spring.datasource.filters=stat,wall,log4j
    # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
    spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    # 合并多个DruidDataSource的监控数据
    #spring.datasource.useGlobalDataSourceStat=true
    
    #视图模型
    spring.thymeleaf.prefix=classpath:/templates/
    spring.thymeleaf.suffix=.html
    spring.thymeleaf.cache=false
    spring.thymeleaf.mode=HTML5
    spring.thymeleaf.encoding=UTF-8
    spring.thymeleaf.content-type=text/html
    spring.thymeleaf.check-template-location=true
    

    main 方法入口

    package liangchong998;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    /** * 程序入口 * */
    @SpringBootApplication
    public class App {    
        public static void main( String[] args ) {   
           SpringApplication.run(App.class, args);    
        }
    }
    

    注册数据库

    package liangchong998.base;
    import com.alibaba.druid.pool.DruidDataSource;
    import com.alibaba.druid.util.StringUtils;
    import com.github.pagehelper.PageHelper;
    import org.apache.ibatis.plugin.Interceptor;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.mybatis.spring.SqlSessionTemplate;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.bind.RelaxedPropertyResolver;
    import org.springframework.context.ApplicationContextException;
    import org.springframework.context.EnvironmentAware;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.env.Environment;
    import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
    import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    import org.springframework.transaction.PlatformTransactionManager;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    import java.io.IOException;
    import java.sql.SQLException;
    import java.util.Arrays;
    import java.util.Properties;
    /** 
     * Created by liangchong998 on 2016/8/18. 
     */
    @Configuration
    @EnableTransactionManagement
    @MapperScan(value = "liangchong998.mapper")
    public class DatabaseConfiguration implements EnvironmentAware { 
        private Environment environment; 
        private RelaxedPropertyResolver propertyResolver; 
        @Override 
        public void setEnvironment(Environment environment) { 
          this.environment = environment; 
          this.propertyResolver = new RelaxedPropertyResolver(environment,"spring.datasource."); 
        } 
        //注册dataSource 
        @Bean(initMethod = "init", destroyMethod = "close") 
        public DruidDataSource dataSource() throws SQLException { 
          if (StringUtils.isEmpty(propertyResolver.getProperty("url"))) { 
            System.out.println("Your database connection pool configuration is incorrect!" 
                + " Please check your Spring profile, current profiles are:"
                + Arrays.toString(environment.getActiveProfiles())); 
             throw new ApplicationContextException( 
                "Database connection pool is not configured correctly"); 
          } 
          DruidDataSource druidDataSource = new DruidDataSource(); 
          druidDataSource.setDriverClassName(propertyResolver.getProperty("driver-class-name")); 
          druidDataSource.setUrl(propertyResolver.getProperty("url")); 
          druidDataSource.setUsername(propertyResolver.getProperty("username")); 
          druidDataSource.setPassword(propertyResolver.getProperty("password")); 
          druidDataSource.setInitialSize(Integer.parseInt(propertyResolver.getProperty("initialSize"))); 
          druidDataSource.setMinIdle(Integer.parseInt(propertyResolver.getProperty("minIdle"))); 
          druidDataSource.setMaxActive(Integer.parseInt(propertyResolver.getProperty("maxActive"))); 
          druidDataSource.setMaxWait(Integer.parseInt(propertyResolver.getProperty("maxWait"))); 
          druidDataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(propertyResolver.getProperty("timeBetweenEvictionRunsMillis"))); 
          druidDataSource.setMinEvictableIdleTimeMillis(Long.parseLong(propertyResolver.getProperty("minEvictableIdleTimeMillis"))); 
          druidDataSource.setValidationQuery(propertyResolver.getProperty("validationQuery")); 
          druidDataSource.setTestWhileIdle(Boolean.parseBoolean(propertyResolver.getProperty("testWhileIdle"))); 
          druidDataSource.setTestOnBorrow(Boolean.parseBoolean(propertyResolver.getProperty("testOnBorrow"))); 
          druidDataSource.setTestOnReturn(Boolean.parseBoolean(propertyResolver.getProperty("testOnReturn"))); 
          druidDataSource.setPoolPreparedStatements(Boolean.parseBoolean(propertyResolver.getProperty("poolPreparedStatements"))); 
          druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(propertyResolver.getProperty("maxPoolPreparedStatementPerConnectionSize"))); 
          druidDataSource.setFilters(propertyResolver.getProperty("filters")); 
          return druidDataSource; 
        } 
    
        @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { 
          SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); 
          sqlSessionFactoryBean.setDataSource(dataSource()); 
          //mybatis分页 
          PageHelper pageHelper = new PageHelper(); 
          Properties props = new Properties(); 
          props.setProperty("dialect", "mysql"); 
          props.setProperty("reasonable", "true"); 
          props.setProperty("supportMethodsArguments", "true"); 
          props.setProperty("returnPageInfo", "check"); 
          props.setProperty("params", "count=countSql"); 
          pageHelper.setProperties(props); //添加插件 
          sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper}); 
          PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); 
          sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/liangchong998/mybatis/*.xml")); 
          return sqlSessionFactoryBean.getObject(); 
        } 
        @Bean public PlatformTransactionManager transactionManager() throws SQLException { 
          return new DataSourceTransactionManager(dataSource()); 
        }
    }
    

    druid 开启监控

    package liangchong998.base;
    
    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;
    /** 
     * Created by liangchong998 on 2016/8/18. 
     */
    @Configuration
    public class DruidConfig { 
      @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", "admin"); 
        reg.addInitParameter("loginPassword", "admin"); 
        return reg; 
      } 
    
      @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; 
       }
    }
    

    controller###

    返回index视图,并传递参数

    package liangchong998.controller;
    import com.github.pagehelper.Page;
    import com.github.pagehelper.PageHelper;
    import liangchong998.mapper.UserInfoMapper;
    import liangchong998.model.UserInfo;
    import org.apache.log4j.Logger;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import java.util.List;
    /** 
     * Created by liangchong998 on 2016/8/18. 
     */
    @Controllerpublic class HomeController { 
    
        private Logger logger = Logger.getLogger(HomeController.class); 
    
        @Autowired private UserInfoMapper userInfoMapper; 
    
        @RequestMapping(value = "/", method = RequestMethod.GET) 
        public String index(Model Model){ 
          Model.addAttribute("name","liangchong998"); 
          return "index"; 
        }
    }
    
    

    index.html

    在 resources 中新建文件夹 templates
    新建 index.html此处注意头文件,这地方是个坑
    IDEA 中 ${name} 下一直有个红线报错,不过不影响程序,也不知道是什么原因。

    <!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <head> 
        <meta charset="UTF-8" /> 
        <title>Title</title>
    </head>
    <body>
      <h2>hello <span th:text="${name}">word</span></h2>
    </body>
    </html>
    

    运行 main 方法
    输入 localhost:8080/

    浏览器 项目 Github :Github 地址

    相关文章

      网友评论

      • a2bf667ad987:private Environment environment;

        语句前面需要添加@Resource注解
      • 7b1f2567e290:启动类上还加句 @ServletComponentScan
        liangchong998:@风2016 不用吧,可以启动的
      • 7b1f2567e290:PageHelper 这个类在引用的包中找不到,请问这个问题要如何解决呀
        liangchong998:@风2016 在maven中有引用jar包,项目已经上传github

      本文标题:spring boot 1.4 整合 mybatis druid

      本文链接:https://www.haomeiwen.com/subject/rwsbsttx.html