SpringBoot Learning --- Integrate JDBC, Druid, MyBatis

Video learning link: [Crazy God Says Java] SpringBoot's latest tutorial IDEA version is easy to understand P31-P33
insert image description here

1. Integrate JDBC

1. Create mybatis data

Free download at station C: click to download
Tencent Weiyun free download: link: https://share.weiyun.com/EsX41IvE password: xxv7fg

This blog mainly uses User_test:
insert image description here

2. Import dependencies

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

insert image description here

3. Write a yaml configuration file (application.yaml)

Replace the account and password with your own database!

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

insert image description here

4. Test class


@SpringBootTest
class SpringbootDataJdbcApplicationTests {
    
    

    //DI注入数据源
    @Autowired
    DataSource dataSource;

    @Test
    public void contextLoads() throws SQLException {
    
    
        //看一下默认数据源
        System.out.println(dataSource.getClass());
        //获得连接
        Connection connection =   dataSource.getConnection();
        System.out.println(connection);
        //关闭连接
        connection.close();
    }
}

insert image description here
running result:

  • After SpringBoot integrates JDBC, connecting to the database becomes very simple
  • The default data source is HikariDataSource

insert image description here

If you want to perform some JDBC operations as before (still the same flavor!):
insert image description here

insert image description here

4.JdbcTemplate (further encapsulated on the basis of jdbc)

  • execute method: can be used to execute any SQL statement, generally used to execute DDL statements;
  • Update method and batchUpdate method: The update method is used to execute statements such as adding, modifying, and deleting; the batchUpdate method is used to execute batch-related statements;
  • query method and queryForXXX method: used to execute query related statements;
  • call method: used to execute stored procedures, function-related statements.

insert image description here
running result:
insert image description here

2. Integrate Druid

1. What is Druid

Druid is a database connection pool implementation on Alibaba's open source platform. It combines the advantages of DB pools such as C3P0 and DBCP, and adds log monitoring. Druid can monitor the execution of DB pool connections and SQL very well. It is a DB connection pool born for monitoring. Druid has deployed more than 600 applications in Alibaba, and has undergone a rigorous test of large-scale deployment in production environments for more than a year. Spring Boot 2.0 and above uses the Hikari data source by default. It can be said that Hikari and Driud are the best data sources on the current Java Web. Let's focus on how Spring Boot integrates the Druid data source and how to implement database monitoring.

Druid's github official website address: https://github.com/alibaba/druid
insert image description here

The basic configuration parameters of com.alibaba.druid.pool.DruidDataSource are as follows:
insert image description here
insert image description here
insert image description here

2. Import dependencies


<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.21</version>
</dependency>

insert image description here

3. Switch data source

It has been said before that Spring Boot 2.0 and above uses the HikariDataSource data source by default, but the data source can be specified through spring.datasource.type.

Add the type configuration in application.yaml:

  type: com.alibaba.druid.pool.DruidDataSource # 自定义数据源

insert image description here
Run the test class:
insert image description here

4. Set data source connection initialization size, maximum number of connections, waiting time, minimum number of connections and other settings

 #Spring Boot 默认是不注入这些属性值的,需要自己绑定
    #druid 数据源专有配置
    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,stat:监控统计、log4j:日志记录、wall:防御sql注入
    #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

insert image description here

5. Import Log4j dependencies

<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

insert image description here

6. Add components to the container

Now programmers need to bind the parameters in the global configuration file for DruidDataSource by themselves, and then add them to the container, instead of using Spring Boot's automatic generation, we need to add the DruidDataSource component to the container and bind the properties;

Create a config file and create a DruidConfig class under that file:

@Configuration
public class DruidConfig {
    
    
    /*
   将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
   绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
   @ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中
   前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
   */
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
    
    
        return new DruidDataSource();
    }

}

insert image description here
prefix = “spring.datasource”:
insert image description here

Test class:
insert image description here
running effect:
insert image description here

7. Configure Druid data source monitoring

The Druid data source has the monitoring function and provides a web interface for users to view. Similar to installing a router, they also provide a default web page. So the first step is to set up Druid's background management page, such as login account, password, etc.; configure background management;

Import web dependencies:

        <!--导入Web依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

insert image description here
Modify the web access port to 8089 (in application.properties):
insert image description here

Add the following method to the DruidConfig class under config:


//配置 Druid 监控管理后台的Servlet;
//内置 Servlet 容器时没有web.xml文件,所以使用 Spring Boot 的注册 Servlet 方式
@Bean
public ServletRegistrationBean statViewServlet() {
    
    
    ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");

    // 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet 
    // 的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
    Map<String, String> initParams = new HashMap<>();
    initParams.put("loginUsername", "admin"); //后台管理界面的登录账号
    initParams.put("loginPassword", "123456"); //后台管理界面的登录密码

    //后台允许谁可以访问
    //initParams.put("allow", "localhost"):表示只有本机可以访问
    //initParams.put("allow", ""):为空或者为null时,表示允许所有访问
    initParams.put("allow", "");
    //deny:Druid 后台拒绝谁访问
    //initParams.put("kuangshen", "192.168.1.20");表示禁止此ip访问

    //设置初始化参数
    bean.setInitParameters(initParams);
    return bean;
}

insert image description here
Run the Web project, open the browser, visit (http://localhost:8089/druid/login.html), and enter the account and password we set in the code:
insert image description here
Running effect:
insert image description here

8. Configure Druid web monitoring filter filter

Add the following method to the DruidConfig class under config:


//配置 Druid 监控 之  web 监控的 filter
//WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
@Bean
public FilterRegistrationBean webStatFilter() {
    
    
    FilterRegistrationBean bean = new FilterRegistrationBean();
    bean.setFilter(new WebStatFilter());

    //exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
    Map<String, String> initParams = new HashMap<>();
    initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");
    bean.setInitParameters(initParams);

    //"/*" 表示过滤所有请求
    bean.setUrlPatterns(Arrays.asList("/*"));
    return bean;
}

insert image description here

3. Integrate MyBatis

1. Import dependencies

     <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

insert image description here

2. Create a pojo file and create a User entity class

import lombok:

    <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

insert image description here
Create User class:
insert image description here

3. Create a mapper file and create the userMapper interface and userMapper.xml under the file

insert image description here

insert image description here
insert image description here

4. Create the controller file and create the UserController class

insert image description here

5. Configure resource filtering in pom.xml

        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>

insert image description here

6. Set type-aliases-package in application.properties

mybatis.type-aliases-package=com.dudu.pojo

insert image description here

7. Running effect

insert image description here
insert image description here

8. If the UserMapper.xml file is not placed under the mapper file under src

insert image description here
This run will report not found:
insert image description here
just set the mybatis.mapper-locations interface in application.properties:

mybatis.mapper-locations=classpath*:/mapper/*.xml

insert image description here

Run it again (problem solved):
insert image description here

4. Source code download

Recently, I am playing the WeChat public account, haha, search for the programmer Gu Ye (or scan the QR code below) on the WeChat public account, reply SpringBoot 整合in the background, and you can get the source code!
insert image description here

Guess you like

Origin blog.csdn.net/weixin_42753193/article/details/123649345