Spring boot JDBC connection database example
The text will introduce several database connection methods based on MySQL database in the web application built by spring boot.
Includes JDBC, JPA, mybatis, multiple data sources, and transactions.
JDBC connection database
1. Property configuration file (application. Properties)
If you use JNDI, you can replace spring URL, username and password of datasource, such as:
It is worth mentioning that both the default datasource configuration of spring boot and your own datasource bean will refer to the property configuration in the external property file. So suppose you define a custom datasource bean, you can set the properties when defining the bean, or externalize the property configuration in the property file in the way of "spring. Datasource. *".
2、pom. XML configuration Maven dependency
3. Java code example
StudentService. java
Student. Java entity class
StudentController. java
The project structure diagram after adding files to the project:
Then start the project and access the address: http://localhost:8080/myspringboot/stu/list The response results are as follows:
Connection pool description
Before Tomcat 7, Tomcat essentially applied DBCP connection pool technology to realize JDBC data sources. However, after Tomcat 7, Tomcat provided a new JDBC connection pool scheme as an alternative or alternative to DBCP, which solved many disadvantages of using DBCP before and improved performance.
Spring boot has prepared the best database connection pool scheme for us. We only need to configure the required connection pool parameters in the property file (such as application. Properties).
We use the Tomcat data source connection pool and need to rely on Tomcat JDBC. As long as spring boot starter JDBC or spring boot starter data JPA dependencies are added to the application, there is no need to worry about this, because Tomcat JDBC dependencies will be added automatically.
If we want to use other methods of connection pooling technology, we can override the automatic configuration of spring boot by configuring our own datasource bean.
See my data source configuration:
Developers who have configured connection pools understand the meaning of these attributes.
We open debug log output, logback Add to XML:
Then start the project and observe the log output. As shown in the following figure, the connection pool is automatically enabled:
I added a filter to the above data source configuration and set the delay time to 0 (deliberately set it very low, please modify it in the actual project):