spring boot 1.4 整合 mybatis druid

来源:互联网 发布:深入浅出数据分析 微盘 编辑:程序博客网 时间:2024/05/20 10:15

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

项目结构目录

结构

maven 引入 spring boot 开发依赖

因为 spring boot 不推荐使用 jsp,所以整合jsp会很麻烦,这里我们用 thymeleaf 模板来作为页面视图
spring-boot-starter-thymeleaf 包含 spring-boot-starter-web,所以不用引入web了

<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.DruidDataSourcespring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://192.168.1.28:3306/chiduspring.datasource.username=rootspring.datasource.password=1qaz2WSX# 下面为连接池的补充设置,应用到上面所有数据源中# 初始化大小,最小,最大spring.datasource.initialSize=5spring.datasource.minIdle=5spring.datasource.maxActive=20# 配置获取连接等待超时的时间spring.datasource.maxWait=60000# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒spring.datasource.timeBetweenEvictionRunsMillis=60000# 配置一个连接在池中最小生存的时间,单位是毫秒spring.datasource.minEvictableIdleTimeMillis=300000spring.datasource.validationQuery=SELECT 1 FROM DUALspring.datasource.testWhileIdle=truespring.datasource.testOnBorrow=falsespring.datasource.testOnReturn=false# 打开PSCache,并且指定每个连接上PSCache的大小spring.datasource.poolPreparedStatements=truespring.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=.htmlspring.thymeleaf.cache=falsespring.thymeleaf.mode=HTML5spring.thymeleaf.encoding=UTF-8spring.thymeleaf.content-type=text/htmlspring.thymeleaf.check-template-location=true

main 方法入口

spring boot 入口

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

注册数据库

spring boot 1.4 后 使用 @MapperScan 来扫描mapper,dao,
不用在接口上 @Mapper 了
添加分页插件

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 开启监控

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. */@Configurationpublic 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;    }}

spring boot 默认的静态资源路径为 resources/static
默认的模板路径为 resources/templates

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>

输入 localhost:8080/

浏览器

项目 Github :Github 地址

0 0