SpringBoot integrates Mybatis with Druid database connection pool, springbootmybatis

Source: Internet
Author: User

SpringBoot integrates Mybatis with Druid database connection pool, springbootmybatis

The following example shows how spring boot integrates Mybatis with Druid database connection pool.

Add the following dependencies to the SpringBoot project:

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

# Configure spring. datasource. url = jdbc: mysql: // 127.0.0.1: 3306/test? UseUnicode = true & characterEncoding = utf8 & useSSL = falsespring. datasource. username = adminspring. datasource. password = adminspring. datasource. driver-class-name = com. mysql. jdbc. driver # connection pool configuration # initialization size, minimum, maximum spring. datasource. initialSize = 5 spring. datasource. minIdle = 5 spring. datasource. maxActive = 20 # configure spring to get the connection wait timeout time. datasource. maxWait = 60000 # How long is the configuration interval before a test is performed to detect idle connections to be closed, in milliseconds spring. datasource. timeBetweenEvictionRunsMillis = 60000 # configure the minimum time for a connection to survive in the pool. The unit is millisecond spring. datasource. minEvictableIdleTimeMillis = 300000 # test whether the connection is valid in sqlspring. datasource. validationQuery = select 'x' # It is recommended that the parameter be set to true without affecting performance and ensuring security # Check when applying for a connection. If the idle time is greater than timeBetweenEvictionRunsMillis, run validationQuery to check whether the connection is valid in spring. datasource. testWhileIdle = true # Run validationQuery to check whether the connection is valid in spring. datasource. testOnBorrow = false # execute validationQuery when returning the connection to check whether the connection is valid spring. datasource. testOnReturn = false # To enable PSCache, the value must be greater than 0. If the value is greater than 0, poolPreparedStatements will automatically trigger the change to truespring. datasource. maxPoolPreparedStatementPerConnectionSize = 20 # The attribute type is string, and the extension plug-in is configured through the alias. Common plug-ins include: # filter for monitoring statistics: stat # filter for logs: log4j # filter against SQL injection: wallspring. datasource. filters = stat, log4j, wall

The data source configuration class performanceconfig. java is created. 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: performanceconfig * @ Date 18-1-2 */@ Configuration @ MapperScan ("com. liao. **. dao ") public class performanceconfig {private static final Logger logger = LoggerFactory. getLogger (performanceconfig. class); @ Autowired private JdbcConfig jdbcConfig; @ Bean @ Primary // In the same DataSource, first use the marked 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 */@ 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 Password */@ Value (" $ {spring. datasource. password} ") private String password;/*** database connection pool initialization size */@ Value (" $ {spring. datasource. initialSize} ") private int initialSize;/*** minimum connections in the database connection pool */@ Value (" $ {spring. datasource. minIdle} ") private int minIdle;/*** maximum number of connections in the database connection pool */@ Value (" $ {spring. datasource. maxActive} ") private int maxActive;/*** get the connection wait timeout time */@ Value (" $ {spring. datasource. maxWait} ") private long maxWait;/*** */@ Value (" $ {spring. datasource. timeBetweenEvictionRunsMillis} ") private long timeBetweenEvictionRunsMillis;/*** minimum time for connecting to the pool */@ Value (" $ {spring. datasource. minEvictableIdleTimeMillis} ") private long minEvictableIdleTimeMillis;/*** test whether the connection is valid SQL */@ Value (" $ {spring. datasource. validationQuery} ") private String validationQuery;/*** checks whether the connection is valid if the idle time is greater than timeBetweenEvictionRunsMillis. */@ 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;/*** 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 plug-in 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 wait () {return timeBetweenEvictionRunsMillis;} public void setTimeBetweenEvictionRunsMillis (long timeBetweenEvictionRunsMillis) {this. response = success;} 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 evaluate () {return maxPoolPreparedStatementPerConnectionSize;} public void setMaxPoolPreparedStatementPerConnectionSize (int maxPoolPreparedStatementPerConnectionSize) {this. maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;} public String getFilters () {return filters;} public void setFilters (String filters) {this. filters = filters ;}}}

Create the 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, equivalent to <tx: annotation-driven/> public class SessionFactoryConfig {/*** mybatis configuration path */private static String MYBATIS_CONFIG = "mybatis-config.xml"; @ Autowired private DataSource; /***** create sqlSessionFactoryBean * and set configtion, for example, hump name. wait * Set mapper ing path * Set datasource data source ** @ Title: createSqlSessionFactoryBean * @ author: hongyangliao * @ Date: 18-1-3 * @ param * @ return org. mybatis. spring. sqlSessionFactoryBean sqlSessionFactoryBean instance * @ throws */@ Bean (name = "sqlSessionFactory") public SqlSessionFactoryBean submit () 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 for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.