SpringBoot-使用Druid数据源整合Mybatis

1、Druid简介:

Druid首先是一个数据库连接池。Druid是目前最好的数据库连接池,在功能、性能、扩展性方面,都超过其他数据库连接池,包括DBCP、C3P0、BoneCP、Proxool、JBoss DataSource。Druid已经在阿里巴巴部署了超过600个应用,经过一年多生产环境大规模部署的严苛考验。Druid是阿里巴巴开发的号称为监控而生的数据库连接池!

同时Druid不仅仅是一个数据库连接池,它包括四个部分:

Druid是一个JDBC组件,它包括三个部分:

  • 基于Filter-Chain模式的插件体系。

  • DruidDataSource 高效可管理的数据库连接池。

  • SQLParser

2、Druid的功能

1、替换DBCP和C3P0。Druid提供了一个高效、功能强大、可扩展性好的数据库连接池。

2、可以监控数据库访问性能,Druid内置提供了一个功能强大的StatFilter插件,能够详细统计SQL的执行性能,这对于线上分析数据库访问性能有帮助。

3、数据库密码加密。直接把数据库密码写在配置文件中,这是不好的行为,容易导致安全问题。DruidDruiver和DruidDataSource都支持PasswordCallback。

4、SQL执行日志,Druid提供了不同的LogFilter,能够支持Common-Logging、Log4j和JdkLog,你可以按需要选择相应的LogFilter,监控你应用的数据库访问情况。

5、扩展JDBC,如果你要对JDBC层有编程的需求,可以通过Druid提供的Filter机制,很方便编写JDBC层的扩展插件。

所以Druid可以:

  • 1、充当数据库连接池
    2、可以监控数据库访问性能

    3、获得SQL执行日志

3、SpringBoot使用Druid

  1. 首先创建一个SpringBoot应用,在创建项目时选择JDBC以及MySQL驱动,让SpringBoot自动装配所需组件

在这里插入图片描述

创建完成后默认的pom.xml文件如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.guih</groupId>
    <artifactId>spring-boot-data-jdbc</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-data-jdbc</name>
    <description>JDBC Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
      <!-- SpringBoot集成的JDBC以及数据库连接包 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
      
        <!-- Druid依赖 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.17</version>
        </dependency>
        <!-- 配置log4j依赖,否则无法正常使用filters过滤器,无法统计SQL语句 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
      
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

  1. 创建 application.yml 文件,配置连接数据库的参数
spring:
  datasource:
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8&useSSL=false
    #这里选择自定义的Druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
		
		#初始化时建立物理连接的个数
    initialSize: 5
    
    #最小连接池数量
    minIdle: 5
    
    #最大连接池数量
    maxActive: 20
    
    #最大的等待时间,单位为毫秒。配置之后,默认启用公平锁,并发效率会有所下降,如果需要可以通过配置useUnfairLock属性为true使用非公平锁
    maxWait: 60000
    
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    
    #用来检测连接是否有效的sql,要求是一个查询语句。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会其作用。
    validationQuery: SELECT 1 FROM DUAL
    
    #建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
    testWhileIdle: true
    
    #申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
    testOnBorrow: false
    
    #归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
    testOnReturn: false
    
    #是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。
    poolPreparedStatements: true
    
    #配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙!!!
    #这里如果直接配置的话启动项目会报错,需要在pom文件中添加log4j日志框架的依赖!!!
		filters: stat,wall,log4j
		
		#每个连接PSCache大小
    maxPoolPreparedStatementPerConnectionSize: 20
    
    #默认多个DruidDataSource的监控数据是各自独立的,在Druid-0.2.17版本之后,支持配置公用监控数据,配置参数为useGlobalDataSourceStat
    useGlobalDataSourceStat: true
    
    #合并SQL以及通过日志记录执行速度大于500ms的SQL
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

  1. 创建对应的数据库以及编写JavaBean
/*
	数据库建表语句
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for department
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `departmentName` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

// JavaBean

package com.guih.data.mybatis.bean;

public class Department {

    private Integer id;
    private String departmentName;

    public void setId(Integer id) {
        this.id = id;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }

    public Integer getId() {
        return id;
    }

    public String getDepartmentName() {
        return departmentName;
    }
}

  1. 配置Druid监控
 @Configuration
 public class DruidConfig {
 
     @Bean
     @ConfigurationProperties(prefix = "spring.datasource")
     public DataSource druid() {
         return new DruidDataSource();
     }
 
     // 管理后台的Servlet
     @Bean
     public ServletRegistrationBean<StatViewServlet> statViewServlet(){
         ServletRegistrationBean<StatViewServlet> servletRegistrationBean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
 
         Map<String,String> map = new HashMap<>();
 
         map.put("loginUserName","admin");
         map.put("loginPassword","123456");
         map.put("allow","");// 允许全部访问
 
         servletRegistrationBean.setInitParameters(map);
 
         return servletRegistrationBean;
     }
 
     // web监控的Filter
     @Bean
     public FilterRegistrationBean<WebStatFilter> statFilter(){
         FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<>(new WebStatFilter());
 
         Map<String,String> initParams = new HashMap<>();
         initParams.put("exclusions","*.js,*.css,/druid/*");
 
         filterRegistrationBean.setInitParameters(initParams);
 
         filterRegistrationBean.setUrlPatterns(Collections.singletonList("/*"));
 
         return filterRegistrationBean;
     }
 }
  1. 编写测试代码
   @Controller
   public class JDBCTest {
   
       @Autowired
       private JdbcTemplate jdbcTemplate;
   
       @RequestMapping("/query")
       @ResponseBody
       public Map<String, Object> query() {
           List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT * FROM test1");
           return list.get(0);
       }
   }
   

这里使用的数据库是本地数据库,数据库中只有一张表,表中数据如下

[

  1. 测试

    启动SpringBoot程序后在浏览器输入 ”localhost:8080/druid“ 会自动跳转到以下页面,说明Druid的Servlet配置成功

    [外链图片转存失败(img-vJiXwJVY-1565848746518)(/Users/guih/Desktop/d33.png)]

    在浏览器输入 ”localhost:8080/query“ 进行测试

    查询结果正常,SQL监控也显示出来了到此,SpringBoot整合Druid数据源就完成了

4、整合Mybatis

  1. 在application.yml文件中设置mybatis配置文件
spring:
  datasource:
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis
    type: com.alibaba.druid.pool.DruidDataSource

    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
#   SpringBoot主程序启动时运行对应的Sql文件,第一次运行就可以了,也可以手动运行
#    schema:
#      - classpath:sql/department.sql
    initialization-mode: always
    
# 在上面的配置文件基础上加上mybatis的配置
mybatis:
  # 指定全局配置文件位置
  config-location: classpath:mybatis/mybatis-config.xml
  # 指定sql映射文件位置
  mapper-locations: classpath:mybatis/mapper/*.xml
debug: true
  1. 编写Mapper文件(使用注解开发和使用配置文件的方式开发)
package com.guih.data.mybatis.mapper;

import com.guih.data.mybatis.bean.Department;
import org.apache.ibatis.annotations.*;

//@Mapper
// 在SpringBoot启动的主程序上配置有Mapper扫描,所以这里不用再次使用 
public interface DepartmentMapper {

  	// 使用注解开发
    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    void insertDepartment(Department department);

    @Select("select * from department where id = #{id}")
    Department queryByID(Integer id);

    // 使用配置文件
    Department queryDept(Integer id);

}

编写完Mapper以后使用注解开发的话是已经可以使用了,但是我们这里注解和配置一起使用,所以还需要编写Mapper.xml文件

  1. 编写对应的Mapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.guih.data.mybatis.mapper.DepartmentMapper">
  <!-- 这里对应着上面Mapper.java文件中的最后一个方法 -->
   <select id="queryDept" parameterType="java.lang.Integer" resultType="com.guih.data.mybatis.bean.Department">
       select * from department where id=#{id}
   </select>

</mapper>
  1. 编写Controller层进行测试
package com.guih.data.mybatis.controller;

import com.guih.data.mybatis.bean.Department;
import com.guih.data.mybatis.mapper.DepartmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CRUDController {

    @Autowired
    private DepartmentMapper departmentMapper;

    // 这个方法是使用注解开发
    @GetMapping("/dept")
    public Department insertDept(Department department) {
        departmentMapper.insertDepartment(department);
        return department;
    }
		// 这个方法使用的是配置文件的方式
    @GetMapping("/dept/{id}")
    public Department queryDept(@PathVariable("id") Integer id) {
        return departmentMapper.queryDept(id);
    }

}

  1. 进行测试

通过测试可以看到,无论是注解开发的还是使用配置文件来配置的都是可以进行对应的操作。

到此SpringBoot整合Druid数据源使用Mybatis就成功了。在最后放上项目的目录截图。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答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提供了非常强大和灵活的数据操作支持和连接池管理,可以有效地提高应用的性能和稳定性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值