spring boot 1.4 整合 mybatis druid

spring boot 1.4 整合 mybatis盛末,使用 druid 數(shù)據(jù)庫(kù)連接池

項(xiàng)目結(jié)構(gòu)目錄 ##
結(jié)構(gòu)

maven 引入 spring boot 開(kāi)發(fā)依賴

  <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可以實(shí)現(xiàn)頁(yè)面熱部署(即頁(yè)面修改后會(huì)立即生效弹惦,這個(gè)可以直接在application.properties文件中配置spring.thymeleaf.cache=false來(lái)實(shí)現(xiàn)),   
     實(shí)現(xiàn)類文件熱部署(類文件修改后不會(huì)立即生效)悄但,實(shí)現(xiàn)對(duì)屬性文件的熱部署棠隐。    即devtools會(huì)監(jiān)聽(tīng)classpath下的文件變動(dòng),并且會(huì)立即重啟應(yīng)用(發(fā)生在保存時(shí)機(jī))檐嚣,注意:因?yàn)槠洳捎玫奶摂M機(jī)機(jī)制助泽,該項(xiàng)重啟是很快的  -->  
    <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 分頁(yè)插件 -->  
    <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>        
          <!-- 我習(xí)慣將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

數(shù)據(jù)庫(kù)連接信息與 druid 的連接池配置信息
thymeleaf 模板的配置

#數(shù)據(jù)庫(kù)配置
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
# 下面為連接池的補(bǔ)充設(shè)置,應(yīng)用到上面所有數(shù)據(jù)源中# 初始化大小嚎京,最小嗡贺,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置獲取連接等待超時(shí)的時(shí)間
spring.datasource.maxWait=60000
# 配置間隔多久才進(jìn)行一次檢測(cè),檢測(cè)需要關(guān)閉的空閑連接鞍帝,單位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一個(gè)連接在池中最小生存的時(shí)間诫睬,單位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打開(kāi)PSCache,并且指定每個(gè)連接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置監(jiān)控統(tǒng)計(jì)攔截的filters帕涌,去掉后監(jiān)控界面sql無(wú)法統(tǒng)計(jì)摄凡,'wall'用于防火墻
spring.datasource.filters=stat,wall,log4j
# 通過(guò)connectProperties屬性來(lái)打開(kāi)mergeSql功能;慢SQL記錄
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多個(gè)DruidDataSource的監(jiān)控?cái)?shù)據(jù)
#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);    
    }
}

注冊(cè)數(shù)據(jù)庫(kù)

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."); 
    } 
    //注冊(cè)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分頁(yè) 
      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 開(kāi)啟監(jiān)控

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視圖蚓曼,并傳遞參數(shù)

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此處注意頭文件亲澡,這地方是個(gè)坑
IDEA 中 ${name} 下一直有個(gè)紅線報(bào)錯(cuò),不過(guò)不影響程序辟躏,也不知道是什么原因谷扣。

<!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>

運(yùn)行 main 方法
輸入 localhost:8080/

瀏覽器
項(xiàng)目 Github :Github 地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末土全,一起剝皮案震驚了整個(gè)濱河市捎琐,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌裹匙,老刑警劉巖瑞凑,帶你破解...
    沈念sama閱讀 222,627評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異概页,居然都是意外死亡籽御,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,180評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)技掏,“玉大人铃将,你說(shuō)我怎么就攤上這事⊙剖幔” “怎么了劲阎?”我有些...
    開(kāi)封第一講書人閱讀 169,346評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)鸠真。 經(jīng)常有香客問(wèn)我悯仙,道長(zhǎng),這世上最難降的妖魔是什么吠卷? 我笑而不...
    開(kāi)封第一講書人閱讀 60,097評(píng)論 1 300
  • 正文 為了忘掉前任锡垄,我火速辦了婚禮,結(jié)果婚禮上祭隔,老公的妹妹穿的比我還像新娘货岭。我一直安慰自己,他們只是感情好序攘,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,100評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布茴她。 她就那樣靜靜地躺著,像睡著了一般程奠。 火紅的嫁衣襯著肌膚如雪丈牢。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 52,696評(píng)論 1 312
  • 那天瞄沙,我揣著相機(jī)與錄音己沛,去河邊找鬼。 笑死距境,一個(gè)胖子當(dāng)著我的面吹牛申尼,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播垫桂,決...
    沈念sama閱讀 41,165評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼师幕,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了诬滩?” 一聲冷哼從身側(cè)響起霹粥,我...
    開(kāi)封第一講書人閱讀 40,108評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎疼鸟,沒(méi)想到半個(gè)月后后控,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,646評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡空镜,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,709評(píng)論 3 342
  • 正文 我和宋清朗相戀三年浩淘,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了捌朴。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,861評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡张抄,死狀恐怖砂蔽,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情署惯,我是刑警寧澤察皇,帶...
    沈念sama閱讀 36,527評(píng)論 5 351
  • 正文 年R本政府宣布,位于F島的核電站泽台,受9級(jí)特大地震影響什荣,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜怀酷,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,196評(píng)論 3 336
  • 文/蒙蒙 一稻爬、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧蜕依,春花似錦桅锄、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 32,698評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至檐束,卻和暖如春辫秧,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背被丧。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,804評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工盟戏, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人甥桂。 一個(gè)月前我還...
    沈念sama閱讀 49,287評(píng)論 3 379
  • 正文 我出身青樓柿究,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親黄选。 傳聞我的和親對(duì)象是個(gè)殘疾皇子蝇摸,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,860評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容