SpringBoot project - integrating mybatis+druid connection pool

The benefits of the druid connection pool will not be discussed. You can download it on Baidu =-=, mainly because I am also a novice. I will hang up my own steps and codes below. (Look directly at the aspect, build directly from 0)

One: Build the springboot+mybatis framework

1: Introduce jar package

<!--web-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

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

		<!--Connect driver-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

		<!--druid datasource-->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.28</version>
		</dependency>

The above are all jar packages required by the framework

2: Create a mybatis-config file, which contains the data source and mybaits settings

<?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>
	<!-- Configure global properties-->
	<settings>
		<!-- Use jdbc's getGeneratedKeys to get the database self-incrementing primary key value -->
		<setting name="useGeneratedKeys" value="true" />

		<!-- Replace column names with column aliases Default: true -->
		<setting name="useColumnLabel" value="true" />

		<!-- Turn on camel case name conversion: Table{create_time} -> Entity{createTime} -->
		<setting name="mapUnderscoreToCamelCase" value="true" />

		<!-- print query statement-->
		<setting name="logImpl" value="STDOUT_LOGGING" />

	</settings>

	<environments default="development">
		<environment id="development">
			<!-- Use JDBC transaction management-->
			<transactionManager type="JDBC" />
			<!-- Database connection pool -->
			<dataSource type="POOLED">
				<property name="driver" value="org.gjt.mm.mysql.Driver"/>
				<property name="url" value="jdbc:mysql://localhost:3306/mybatis "/>
				<property name="username" value="root"/>
				<property name="password" value="123456"/>
			</dataSource>
		</environment>
	</environments>
	
</configuration>

Because the druid data source connection pool is used here, the dataSource does not need to be configured.

3: Create the mapping xml file AreaMapper.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.project.myo2o.mapper.AreaMapper">

	<select id="queryArea" resultType="com.project.myo2o.entity.Area">
		SELECT
		*
		FROM
		tb_area
		ORDER BY
		priority DESC
	</select>
</mapper>
<mapper namespace="com.project.myo2o.mapper.AreaMapper"> The namespace is the location of the interface mapper
<select id="queryArea" resultType="com.project.myo2o.entity.Area">id corresponds to the method name in the interface, resultType corresponds to the result set queried, and resultMap can be customized

4: Create a mapper interface class

import com.project.myo2o.entity.Area;

import java.util.List;
@Mapper//Must be marked as mapper
public interface AreaMapper {
    List<Area> queryArea();
}

Two: Join the druid connection pool

1: Write the data source configuration class DruidDBConfig

import java.sql.SQLException;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.alibaba.druid.pool.DruidDataSource;

@Configuration
public class DruidDBConfig {
    private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);


    @Value("${spring.datasource.url}")
    private String dbUrl;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.driverClassName}")
    private String driverClassName;

    @Value("${spring.datasource.initialSize}")
    private int initialSize;

    @Value("${spring.datasource.minIdle}")
    private int minIdle;

    @Value("${spring.datasource.maxActive}")
    private int maxActive;

    @Value("${spring.datasource.maxWait}")
    private int maxWait;

    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;

    @Value("${spring.datasource.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;

    @Value("${spring.datasource.validationQuery}")
    private String validationQuery;

    @Value("${spring.datasource.testWhileIdle}")
    private boolean testWhileIdle;

    @Value("${spring.datasource.testOnBorrow}")
    private boolean testOnBorrow;

    @Value("${spring.datasource.testOnReturn}")
    private boolean testOnReturn;

    @Value("${spring.datasource.poolPreparedStatements}")
    private boolean poolPreparedStatements;

    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
    private int maxPoolPreparedStatementPerConnectionSize;

    @Value("${spring.datasource.filters}")
    private String filters;

    @Value("{spring.datasource.connectionProperties}")
    private String connectionProperties;

    @Bean //declare it as a Bean instance
    @Primary //In the same DataSource, first use the marked DataSource
    public DataSource dataSource(){
        DruidDataSource datasource = new DruidDataSource();

        datasource.setUrl(this.dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);

        //configuration
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis (timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis (minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle (testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn (testOnReturn);
        datasource.setPoolPreparedStatements (poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        try {
            datasource.setFilters(filters);
        } catch (SQLException e) {
            logger.error("druid configuration initialization filter", e);
        }
        datasource.setConnectionProperties(connectionProperties);

        return datasource;
    }
}

The @primary annotation is mainly for mybatis to specify the data source as this dataSuorce class when loading the data source

2: Create application.yml file

#Configure mysql
spring:
  datasource:
    url: jdbc:mysql://localhost:3307/myo2o?useUnique=true&characterEncoding=utf8&useSSL=false
    username: root
    password: 123456
    driverClassName: com.mysql.jdbc.Driver
    #Druid connection pool configuration
    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
    maxPoolPreparedStatementPerConnectionSize: 20
    filters: stat,wall,slf4j
    connectionProperties.druid.stat.mergeSql: true;
    connectionProperties.druid.stat.slowSqlMillis: 5000
#Mybatis
mybatis:
  #Load mybatis main configuration class
  config-location: classpath:mybatis/mybatis-config.xml
  #Load mapper configuration class
  mapper-locations: classpath:mybatis/mapper/*.xml
  #Load mapper entity class
  type-aliases-package: com.project.myo2o.entity

The data of the connection pool and database connection information are configured in yml. When mybatis creates a dataSource instance, it will execute the DruidDBConfig class, and the DruidDBConfig class will read and write the content of the yml file.

mybatis:
  #Load mybatis main configuration class
  config-location: classpath:mybatis/mybatis-config.xml
  #Load mapper configuration class
  mapper-locations: classpath:mybatis/mapper/*.xml
  #Load mapper entity class
  type-aliases-package: com.project.myo2o.entity

The above file will scan the mabatis configuration file.

Basically, the above files can be run, but the druid connection pool can also be monitored, configure the following two files

DruidStatFilter.java

import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

import com.alibaba.druid.support.http.WebStatFilter;

@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",
        initParams={
                @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")//忽略资源
        }
)
public class DruidStatFilter extends WebStatFilter {

}
DruidStatViewServlet.java
import com.alibaba.druid.support.http.StatViewServlet;

import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;

@WebServlet(urlPatterns="/druid/*",
        initParams={
                @WebInitParam(name="allow",value=""),// IP whitelist (no configuration or empty, all access is allowed)
                @WebInitParam(name="deny",value=""),// IP blacklist (when there is a common one, deny takes precedence over allow)
                @WebInitParam(name="loginUsername",value="root"),// username
                @WebInitParam(name="loginPassword",value="123"),// 密码
                @WebInitParam(name="resetEnable",value="false")// Disable "Reset All" function on HTML page
        })
public class DruidStatViewServlet extends StatViewServlet {
    private static final long serialVersionUID = -2688872071445249539L;
}

After running, enter http://localhost:8080/druid/login.html and enter the username and password set above to log in to view.

Three: Summary

The source code is uploaded to csdn, and you can download and view it if you need it. A complete framework for beginners

https://download.csdn.net/download/qq_36784299/10402440

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326065452&siteId=291194637