SpringBoot学习:整合MyBatis,使用Druid连接池

项目下载地址:http://download.csdn.NET/detail/aqsunkai/9805821

(一)添加pom依赖:

<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.2.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.6</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.29</version>
    </dependency>
(二)项目结构如下:

mapper接口在java目录下,相应的写sql语句的xml在resource目录下,在Application启动类中加入注解:

@ServletComponentScan
@MapperScan("com.sun.**.mapper") //配置扫描mapper接口的地址
@ServletComponentScan 设置启动时spring能够扫描到我们自己编写的servlet和filter, 用于Druid监控

@MapperScan 用于扫描的mapper接口

在配置文件中加入:

# mybatis_config
mybatis:
    mapper-locations: classpath:mapper/**/*.xml
#datasource
spring:
    datasource:
        name: era
        url: jdbc:mysql://localhost:3306/spring_boot?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
        username: root
        password: 123456
        # 使用druid数据源
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        # 下面为连接池的补充设置,应用到上面所有数据源中
        # 初始化大小,最小,最大
        initialSize: 5
        minIdle: 5
        maxActive: 20
        # 配置获取连接等待超时的时间
        maxWait: 60000
        # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        timeBetweenEvictionRunsMillis: 60000
        # 配置一个连接在池中最小生存的时间,单位是毫秒
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 1 FROM DUAL
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        # 打开PSCache,并且指定每个连接上PSCache的大小
        poolPreparedStatements: true
        maxPoolPreparedStatementPerConnectionSize: 20
        # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
        spring.datasource.filters: stat,wall,log4j
        # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
        # 合并多个DruidDataSource的监控数据
        #useGlobalDataSourceStat: true

用于扫描mybatis的映射文件xml,和加载连接池

日志文件中加入:

<!--输出sql语句-->
    <logger name="com.sun" level="debug" />
用于在控制台打印sql语句

DataSource的配置启动管理类如下:

package com.sun.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.alibaba.druid.support.spring.stat.DruidStatInterceptor;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
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.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableTransactionManagement
/**
 * Druid的DataResource配置类
 * 凡是被Spring管理的类,实现接口 EnvironmentAware 重写方法 setEnvironment 可以在工程启动时,
 * 获取到系统环境变量和application配置文件中的变量。 还有一种方式是采用注解的方式获取 @value("${变量的key值}")
 * 获取application配置文件中的变量。 这里采用第一种要方便些
 * Created by sun on 2017-1-20.
 */
public class DruidDataSourceConfig implements EnvironmentAware {

	private RelaxedPropertyResolver propertyResolver;

	public void setEnvironment(Environment env) {
		this.propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
	}

	@Bean
	public DataSource dataSource() {
		DruidDataSource datasource = new DruidDataSource();
		datasource.setUrl(propertyResolver.getProperty("url"));
		datasource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
		datasource.setUsername(propertyResolver.getProperty("username"));
		datasource.setPassword(propertyResolver.getProperty("password"));
		datasource.setInitialSize(Integer.valueOf(propertyResolver.getProperty("initialSize")));
		datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("minIdle")));
		datasource.setMaxWait(Long.valueOf(propertyResolver.getProperty("maxWait")));
		datasource.setMaxActive(Integer.valueOf(propertyResolver.getProperty("maxActive")));
		datasource.setMinEvictableIdleTimeMillis(
				Long.valueOf(propertyResolver.getProperty("minEvictableIdleTimeMillis")));
		try {
			datasource.setFilters("stat,wall");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return datasource;
	}

	@Bean
	public ServletRegistrationBean druidServlet() {
		ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
		servletRegistrationBean.setServlet(new StatViewServlet());
		servletRegistrationBean.addUrlMappings("/druid/*");
		Map<String, String> initParameters = new HashMap<String, String>();
		// initParameters.put("loginUsername", "druid");// 用户名
		// initParameters.put("loginPassword", "druid");// 密码
		initParameters.put("resetEnable", "false");// 禁用HTML页面上的“Reset All”功能
		initParameters.put("allow", "127.0.0.1"); // IP白名单 (没有配置或者为空,则允许所有访问)
		// initParameters.put("deny", "192.168.20.38");// IP黑名单
		// (存在共同时,deny优先于allow)
		servletRegistrationBean.setInitParameters(initParameters);
		return servletRegistrationBean;
	}

	@Bean
	public FilterRegistrationBean filterRegistrationBean() {
		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
		filterRegistrationBean.setFilter(new WebStatFilter());
		filterRegistrationBean.addUrlPatterns("/*");
		filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
		return filterRegistrationBean;
	}

	// 按照BeanId来拦截配置 用来bean的监控
	@Bean(value = "druid-stat-interceptor")
	public DruidStatInterceptor DruidStatInterceptor() {
		DruidStatInterceptor druidStatInterceptor = new DruidStatInterceptor();
		return druidStatInterceptor;
	}

	@Bean
	public BeanNameAutoProxyCreator beanNameAutoProxyCreator() {
		BeanNameAutoProxyCreator beanNameAutoProxyCreator = new BeanNameAutoProxyCreator();
		beanNameAutoProxyCreator.setProxyTargetClass(true);
		// 设置要监控的bean的id
		//beanNameAutoProxyCreator.setBeanNames("sysRoleMapper","loginController");
		beanNameAutoProxyCreator.setInterceptorNames("druid-stat-interceptor");
		return beanNameAutoProxyCreator;
	}

}

后台执行在控制台上输出:

2017-04-07 21:25:15.904  INFO 10500 --- [io-8080-exec-10] c.s.p.controller.UserController          : 哈哈哈
2017-04-07 21:25:15.908 DEBUG 10500 --- [io-8080-exec-10] c.s.p.m.UserMapper.selectByPrimaryKey    : ==>  Preparing: select id, nickname, email, pswd, create_time, last_login_time, status from sys_user where id = ? 
2017-04-07 21:25:15.911 DEBUG 10500 --- [io-8080-exec-10] c.s.p.m.UserMapper.selectByPrimaryKey    : ==> Parameters: 1(Integer)
2017-04-07 21:25:15.918 DEBUG 10500 --- [io-8080-exec-10] c.s.p.m.UserMapper.selectByPrimaryKey    : <==      Total: 1
2017-04-07 21:25:15.920  INFO 10500 --- [io-8080-exec-10] c.s.p.controller.UserController          : admin
在页面上输入http://localhost:8080/boot/druid/可以看到监控到的sql语句执行情况:

  • 10
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
### 回答1: Spring Boot是一个快速开发框架,而MyBatis是一个流行的ORM框架,Druid是一个高性能的数据库连接。将它们整合在一起可以提高开发效率和系统性能。具体步骤如下: 1. 引入相关依赖:在pom.xml文件中添加spring-boot-starter-jdbc、mybatis-spring-boot-starter和druid-spring-boot-starter依赖。 2. 配置数据源:在application.properties文件中配置数据源信息,包括数据库URL、用户名、密码等。 3. 配置MyBatis:在application.properties文件中配置MyBatis相关信息,包括mapper文件路径、实体类包路径等。 4. 配置Druid:在application.properties文件中配置Druid相关信息,包括连接大小、监控页面路径等。 5. 编写Mapper接口和SQL语句:在Mapper接口中定义SQL语句,并使用@Mapper注解标注该接口。 6. 编写Service层和Controller层:在Service层中调用Mapper接口,实现业务逻辑;在Controller层中处理请求和响应。 7. 启动应用程序:使用Spring Boot的启动器启动应用程序,访问相关接口即可。 总之,整合Spring Boot、MyBatisDruid可以让我们更方便地开发数据库应用程序,提高开发效率和系统性能。 ### 回答2: Spring Boot 是目前非常热门的一种快速构建 web 应用程序的框架,而 Mybatis 是一款非常流行的 Java 数据库持久化框架,Druid 是阿里巴巴开发的数据库连接和监控工具。Spring Boot 整合 MybatisDruid 的开发方式比较简单,只需要进行相应的配置即可。 首先,在 pom.xml 文件中添加 MybatisDruid 的依赖: ``` <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>${druid.version}</version> </dependency> ``` 然后,在 application.yml 或 application.properties 中添加相应的配置,以下是一个示例: ``` spring: datasource: type: com.alibaba.druid.pool.DruidDataSource username: root password: root url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.jdbc.Driver druid: min-idle: 5 max-active: 20 initial-size: 5 test-on-borrow: true validation-query: SELECT 1 mybatis: mapper-locations: classpath:mapper/*.xml ``` 其中,spring.datasource 下的配置是数据库连接相关的配置,druid 下的配置是连接相关的配置,mybatis 下的配置是 Mybatis 相关的配置。 最后,在需要使用 Mybatis 的类上添加 @Mapper 注解即可,例如: ``` @Mapper public interface UserDao { List<User> selectAll(); void insert(User user); } ``` 这样,我们就通过 Spring Boot 整合MybatisDruid,并且可以方便地使用它们来访问数据库。同时,Druid 还提供了一些监控和统计功能,可以方便地了解应用程序访问数据库的性能和健康情况。 ### 回答3: 随着互联网应用越来越普及,Java Web开发也变得越来越火热,相应的Spring Boot、MyBatisDruid等技术也得到了广泛的应用。其中,Spring Boot是基于Spring Framework的一种全新框架,通过封装成熟的框架和工具,提高了开发效率,减少了配置量;MyBatis是一款优秀的基于Java的ORM框架,可以让开发人员更加专注于SQL本身,而无需过多关注底层的操作。Druid是一个强大的数据库连接,具有监控、性能分析、SQL注入检查和防御、不同操作系统适配等特点,能够有效提高应用的性能和稳定性。 Spring Boot整合MyBatisDruid,可以将这三个技术更有效地结合起来,发挥它们的优点。 具体步骤如下: 1. 创建基于Spring Boot的Web工程,并在pom.xml文件中引入相关依赖。 ```xml <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.22</version> </dependency> ``` 2. 创建数据库连接的配置文件application.properties。 ```properties spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&allowMultiQueries=true spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver mybatis.config-location=classpath:mybatis/mybatis-config.xml mybatis.mapper-locations=classpath:com/example/mapper/*Mapper.xml mybatis.type-aliases-package=com.example.entity # Druid数据源配置 # 初始化大小、最小、最大连接数 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.maxEvictableIdleTimeMillis=900000 # 配置连接中的连接创建时的默认自动提交配置 spring.datasource.defaultAutoCommit=true # 对于长时间不使用连接强制关闭 spring.datasource.removeAbandoned=true spring.datasource.removeAbandonedTimeout=1800 spring.datasource.logAbandoned=true spring.datasource.validationQuery=SELECT 1 FROM DUAL spring.datasource.testWhileIdle=true spring.datasource.testOnBorrow=false spring.datasource.testOnReturn=false spring.datasource.filters=stat,wall,log4j ``` 3. 创建MyBatis的配置文件mybatis-config.xml。 ```xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="mapUnderscoreToCamelCase" value="true" /> <setting name="logImpl" value="LOG4J" /> </settings> </configuration> ``` 4. 在Spring Boot的启动类上添加@Configuration注解,并通过@Bean注解来配置SqlSessionFactory和SqlSessionTemplate。 ```java @SpringBootApplication @Configuration @MapperScan(basePackages = "com.example.mapper") public class Application { @Autowired DataSource dataSource; @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); return factoryBean.getObject(); } @Bean public SqlSessionTemplate sqlSessionTemplate() throws Exception { SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory()); return sqlSessionTemplate; } public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 5. 创建Mapper接口和对应的XML文件。 ```java public interface UserMapper { @Select("SELECT * FROM user WHERE id = #{id}") User selectUserById(int id); } ``` ```xml <mapper namespace="com.example.mapper.UserMapper"> <resultMap id="userMap" type="com.example.entity.User"> <id column="id" property="id" jdbcType="INTEGER"/> <result column="username" property="username" jdbcType="VARCHAR"/> <result column="password" property="password" jdbcType="VARCHAR"/> <result column="age" property="age" jdbcType="VARCHAR"/> </resultMap> <select id="selectUserById" resultMap="userMap"> SELECT id, username, password, age FROM user WHERE id = #{id} </select> </mapper> ``` 6. 创建实体类,并注入Mapper接口到Service中进行操作。 ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User selectById(int id) { return userMapper.selectUserById(id); } } ``` 7. 创建Controller,提供对外RESTful API接口。 ```java @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") public User selectById(@PathVariable int id) { return userService.selectById(id); } } ``` 综上,以上是Spring Boot整合MyBatisDruid的流程。由于Spring Boot的封装,开发人员只需要关注业务逻辑的处理,而无需过多关注底层技术的实现细节,大大提高了开发效率。同时,MyBatisDruid提供了非常强大和灵活的数据操作支持和连接管理,可以有效地提高应用的性能和稳定性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值