spring boot 1.4 整合 mybatis druid

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 地址

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,293评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,604评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,958评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,729评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,719评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,630评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,000评论 3 397
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,665评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,909评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,646评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,726评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,400评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,986评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,959评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,996评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,481评论 2 342

推荐阅读更多精彩内容