Connect Spring Boot JDBC to the database

Source: Internet
Author: User

Connect Spring Boot JDBC to the database

This article introduces several MYSQL-based database connection methods in Web applications built by Spring Boot.
Including JDBC, JPA, MyBatis, multiple data sources and transactions.

Connect to the database through JDBC

1. Property configuration file (application. properties)

spring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=com.mysql.jdbc.Driver

If JNDI is used, the url, username, and password of spring. datasource can be replaced, for example:

spring.datasource.jndi-name=java:tomcat/datasources/example

It is worth mentioning that both the default DataSource configuration of Spring Boot and your own DataSource bean will reference the attribute configuration in the external attribute file. Therefore, assume that you can set attributes for custom DataSource bean when defining bean, or you can set attributes as "spring. datasource. *" in the attribute file.

2. Configure maven dependency in pom. xml

mysqlmysql-connector-javaorg.springframework.bootspring-boot-starter-jdbc

3. Java code example

StudentService. java

Package org. springboot. sample. service; import java. SQL. resultSet; import java. SQL. SQLException; import java. util. list; import org. springboot. sample. entity. student; import org. springframework. beans. factory. annotation. autowired; import org. springframework. jdbc. core. jdbcTemplate; import org. springframework. jdbc. core. rowMapper; import org. springframework. stereotype. service;/* Studeng Service ** @ author single Hongyu (365384722) * @ myblog http://blog.csdn.net/catoop/ * @ create January 12, 2016 */@ Servicepublic class StudentService {@ Autowired private JdbcTemplate jdbcTemplate; public ListgetList () {String SQL = "SELECT ID, NAME, SCORE_SUM, SCORE_AVG, AGE FROM STUDENT"; return (List) jdbcTemplate. query (SQL, new RowMapper () {@ Override public Student mapRow (ResultSet rs, int rowNum) throws SQLException {Student stu = new Student (); stu. setId (rs. getInt ("ID"); stu. setAge (rs. getInt ("AGE"); stu. setName (rs. getString ("NAME"); stu. setSumScore (rs. getString ("SCORE_SUM"); stu. setAvgScore (rs. getString ("SCORE_AVG"); return stu ;}});}}

Student. java entity class

Package org. springboot. sample. entity; import java. io. serializable;/*** Student Entity ** @ author single Hongyu (365384722) * @ myblog http://blog.csdn.net/catoop/ * @ create January 12, 2016 */public class Student implements Serializable {private static final long serialVersionUID = 2120869894112984147L; private int id; private String name; private String sumScore; private String avgScore; private int age; // Save the article length. The get set method is omitted}

StudentController. java

Package org. springboot. sample. controller; import java. util. list; import org. slf4j. logger; import org. slf4j. loggerFactory; import org. springboot. sample. entity. student; import org. springboot. sample. service. studentService; import org. springframework. beans. factory. annotation. autowired; import org. springframework. web. bind. annotation. requestMapping; import org. springframework. web. bind. annotation. restController; @ RestController @ RequestMapping ("/stu") public class StudentController {private static final Logger logger = LoggerFactory. getLogger (StudentController. class); @ Autowired private StudentService studentService; @ RequestMapping ("/list") public ListgetStus () {logger.info ("read Student set from database"); return studentService. getList ();}}

After adding files to a project, the project structure is as follows:

Start the project and the response is as follows:

[{Id: 1, name: "Xiao Ming", sumScore: "252", avgScore: "84", age: 1 },{ id: 2, name: "Xiao Wang ", sumScore: "187", avgScore: "62.3", age: 1 },{ id: 3, name: "Lili", sumScore: "", avgScore: "", age: 0 },{ id: 4, name: "", sumScore: "230", avgScore: "76.7", age: 1 },{ id: 5, name: "damao", sumScore: "", avgScore: "", age: 0 },{ id: 6, name: "Liangzi", sumScore: "0", avgScore: "0", age: 1}]
Connection pool description

Before Tomcat 7, Tomcat basically applied the DBCP connection pool technology to implement the JDBC data source. However, after Tomcat 7, Tomcat provided a new JDBC connection pool solution as a replacement or alternative solution for DBCP, solved many disadvantages of using DBCP before and improved the performance. Spring Boot has prepared the best database connection pool solution. You only need to configure the required connection pool parameters in the attribute 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 dependency is added to the application, you do not need to worry about this because the tomcat-jdbc dependency will be automatically added.
If we want to use other connection pool technologies, we only need to configure our own DataSource bean to overwrite the automatic configuration of Spring Boot.

See my data source Configuration:

spring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.max-idle=10spring.datasource.max-wait=10000spring.datasource.min-idle=5spring.datasource.initial-size=5spring.datasource.validation-query=SELECT 1spring.datasource.test-on-borrow=falsespring.datasource.test-while-idle=truespring.datasource.time-between-eviction-runs-millis=18800spring.datasource.jdbc-interceptors=ConnectionState;SlowQueryReport(threshold=0)

Developers who have configured connection pools have a certain understanding of the meaning of these attributes.

Open the DEBUG log output and add the following to logback. xml:


Start the project and observe the log output. The connection pool is automatically enabled:

I added a filter in the above data source configuration and set the delay time to 0 (deliberately set low, Please modify the actual project ):

spring.datasource.jdbc-interceptors=ConnectionState;SlowQueryReport(threshold=0)

At this time, observe the log and you will find that the framework will automatically warn the output of data queries later than this time, as shown below:

2016-01-12 23:27:06.710  WARN 17644 --- [nio-8080-exec-1] o.a.t.j.p.interceptor.SlowQueryReport    : Slow Query Report SQL=SELECT ID,NAME,SCORE_SUM,SCORE_AVG, AGE   FROM STUDENT; time=3 ms;
 

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.