This example shares with you the method of integrating SpringBoot with Mybatis using Druid database connection pool. The specific content is as follows
In SpringBoot project, add the following dependencies
<!-- spring mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- druid database connection pool--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.26</version> </dependency>
In the resource directory, create the jdbc.properties configuration file and add the following configuration
#Database configuration spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=falsspring.datasource.username=adminspring.datasource.password=adminspring.datasource.driver-class-name=com.mysql.jdbc.Driver# Connection pool configuration# Initialize size, minimum, maximum spring.datasource.initialSize=5 spring.datasource.minIdle=5 spring.datasource.maxActive=20 # Configure the time to get the connection waiting timeout spring.datasource.maxWait=60000 # Configure how long it takes to perform a detection interval to detect idle connections that need to be closed, in milliseconds spring.datasource.timeBetweenEvictionRunsMillis=60000 # Configure the minimum time to survive in the pool, in milliseconds spring.datasource.minEvictableIdleTimeMillis=300000# Test whether the connection is valid sqlspring.datasource.validationQuery=select 'x'# It is recommended to configure it to true, not affect performance and ensure security# When applying for a connection, if the idle time is greater than timeBetweenEvictionRunsMillis, execute validationQuery to detect whether the connection is valid spring.datasource.testWhileIdle=true# When applying for a connection, execute validationQuery to detect whether the connection is valid spring.datasource.testOnBorrow=false# When returning the connection, execute validationQuery to detect whether the connection is valid spring.datasource.testOnReturn=false# To enable PSCache, it must be configured to be greater than 0. When it is greater than 0, poolPreparedStatements will be automatically triggered to be truespring.datasource.maxPoolPreparedStatementPerConnectionSize=20# The attribute type is a string. The extension plug-in is configured by alias. Common plug-ins are: # for monitoring statistics: stat# for logging filter: log4j# for defense against sql injection: wallspring.datasource.filters=stat,log4j,wall
Create the data source configuration class DataSourceConfig.java, the code is as follows
package com.liao.mybatis;import com.alibaba.druid.pool.DruidDataSource;import org.mybatis.spring.annotation.MapperScan;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;import org.springframework.stereotype.Component;import javax.sql.DataSource;import java.sql.SQLException;/** * Data Source* * @author hongyangliao * @ClassName: DataSourceConfig * @Date 18-1-2 8:56 pm */@Configuration@MapperScan("com.liao.**.dao")public class DataSourceConfig { private static final Logger logger = LoggerFactory.getLogger(DataSourceConfig.class); @Autowired private JdbcConfig jdbcConfig; @Bean @Primary //In the same DataSource, first use the annotated DataSource public DataSource dataSource() { DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setUrl(jdbcConfig.getUrl()); druidDataSource.setUsername(jdbcConfig.getUserName()); druidDataSource.setPassword(jdbcConfig.getPassword()); druidDataSource.setInitialSize(jdbcConfig.getInitialSize()); druidDataSource.setMinIdle(jdbcConfig.getMinIdle()); druidDataSource.setMaxActive(jdbcConfig.getMaxActive()); druidDataSource.setTimeBetweenEvictionRunsMillis(jdbcConfig.getTimeBetweenEvictionRunsMillis()); druidDataSource.setMinEvictableIdleTimeMillis(jdbcConfig.getMinEvictableIdleTimeMillis()); druidDataSource.setValidationQuery(jdbcConfig.getValidationQuery()); druidDataSource.setTestWhileIdle(jdbcConfig.isTestWhileIdle()); druidDataSource.setTestOnBorrow(jdbcConfig.isTestOnBorrow()); druidDataSource.setTestOnReturn(jdbcConfig.isTestOnReturn()); druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(jdbcConfig.getMaxPoolPreparedStatementPerConnectionSize()); try { druidDataSource.setFilters(jdbcConfig.getFilters()); } catch (SQLException e) { if (logger.isInfoEnabled()) { logger.info(e.getMessage(), e); } } return druidDataSource; } /** * Jdbc configuration class* * @author hongyangliao * @ClassName: JdbcConfig * @Date 18-1-2 9:00 pm */ @PropertySource(value = "classpath:jdbc.properties") @Component public static class JdbcConfig { /** * Database username*/ @Value("${spring.datasource.username}") private String userName; /** * Driver name*/ @Value("${spring.datasource.driver-class-name}") private String driverClass; /** * Database connection url */ @Value("${spring.datasource.url}") private String url; /** * Database connection pool initialization size*/ @Value("${spring.datasource.initialSize}") private int initialSize; /** * Minimum number of connections in database connection pool*/ @Value("${spring.datasource.minIdle}") private int minIdle; /** * Maximum number of connections in database connection pool*/ @Value("${spring.datasource.maxActive}") private int maxActive; /** * Get the time when the connection waits for timeout*/ @Value("${spring.datasource.maxWait}") private long maxWait; /** * How often to detect*/ @Value("${spring.datasource.timeBetweenEvictionRunsMillis}") private long timeBetweenEvictionRunsMillis; /** * Minimum time for a connection to survive in the pool*/ @Value("${spring.datasource.minEvictableIdleTimeMillis}") private long minEvictableIdleTimeMillis; /** * SQL to test whether the connection is valid */ @Value("${spring.datasource.validationQuery}") private String validationQuery; /** * When applying for a connection, if the idle time is greater than timeBetweenEvictionRunsMillis, check whether the connection is valid */ @Value("${spring.datasource.testWhileIdle}") private boolean testWhileIdle; /** * When applying for a connection, check whether the connection is valid */ @Value("${spring.datasource.testOnBorrow}") private boolean testOnBorrow; /** * When returning the connection, check whether the connection is valid */ @Value("${spring.datasource.testOnReturn}") private boolean testOnReturn; /** * PSCache size*/ @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}") private int maxPoolPreparedStatementPerConnectionSize; /** *Configure the extension plugin by alias*/ @Value("${spring.datasource.filters}") private String filters; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getDriverClass() { return driverClass; } public void setDriverClass(String driverClass) { this.driverClass = driverClass; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getInitialSize() { return initialSize; } public void setInitialSize(int initialSize) { this.initialSize = initialSize; } public int getMinIdle() { return minIdle; } public void setMinIdle(int minIdle) { this.minIdle = minIdle; } public int getMaxActive() { return maxActive; } public void setMaxActive(int maxActive) { this.maxActive = maxActive; } public long getMaxWait() { return maxWait; } public void setMaxWait(long maxWait) { this.maxWait = maxWait; } public long getTimeBetweenEvictionRunsMillis() { return timeBetweenEvictionRunsMillis; } public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) { this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; } public long getMinEvictableIdleTimeMillis() { return minEvictableIdleTimeMillis; } public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; } public String getValidationQuery() { return validationQuery; } public void setValidationQuery(String validationQuery) { this.validationQuery = validationQuery; } public boolean isTestWhileIdle() { return testWhileIdle; } public void setTestWhileIdle(boolean testWhileIdle) { this.testWhileIdle = testWhileIdle; } public boolean isTestOnBorrow() { return testOnBorrow; } public void setTestOnBorrow(boolean testOnBorrow) { this.testOnBorrow = testOnBorrow; } public boolean isTestOnReturn() { return testOnReturn; } public void setTestOnReturn(boolean testOnReturn) { this.testOnReturn = testOnReturn; } public int getMaxPoolPreparedStatementPerConnectionSize() { return maxPoolPreparedStatementPerConnectionSize; } public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) { this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize; } public String getFilters() { return filters; } public void setFilters(String filters) { this.filters = filters; } }}Create Session Factory Configuration Class SessionFactoryConfig.java, the code is as follows
package com.liao.mybatis;import java.io.IOException;import javax.sql.DataSource;import org.mybatis.spring.SqlSessionFactoryBean;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.ClassPathResource;import org.springframework.transaction.annotation.EnableTransactionManagement;@Configuration@EnableTransactionManagement // Enable annotation transaction management, which is equivalent to the xml configuration method <tx:annotation-driven />public class SessionFactoryConfig { /** * mybatis configuration path */ private static String MYBATIS_CONFIG = "mybatis-config.xml"; @Autowired private DataSource dataSource; /*** * Create sqlSessionFactoryBean * and set configtion such as camel naming. etc* Set mapper mapping path * Set datasource data source * * @Title: createSqlSessionFactoryBean * @author: hongyangliao * @Date: 18-1-3 9:52 am * @param * @return org.mybatis.spring.SqlSessionFactoryBean sqlSessionFactoryBean instance* @throws */ @Bean(name = "sqlSessionFactory") public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException { SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean(); // Set mybatis configuration scan path sqlSessionFactory.setConfigLocation(new ClassPathResource(MYBATIS_CONFIG)); // Set datasource sqlSessionFactory.setDataSource(dataSource); return sqlSessionFactory; }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.