adding JDBC modules and MySQL database drivers to Pom.xml
<!--JDBC - <Dependency> <groupId>Org.springframework.boot</groupId> <Artifactid>Spring-boot-starter-jdbc</Artifactid> </Dependency> <!--MySQL Database driver - <Dependency> <groupId>Mysql</groupId> <Artifactid>Mysql-connector-java</Artifactid> </Dependency>
Application.properties
The Spring boot JDBC module loads the following parameters, and the MySQL driver is recognized and automatically loaded according to the URL, automatically creating the DB instance, and automatically implementing the connection pool.
spring.datasource.url=jdbc:mysql://localhost:3306/david2018_db?characterencoding= utf8spring.datasource.username=rootspring.datasource.password=1234
Hellodao.java
The JDBC module also automatically creates a JdbcTemplate instance that can be injected directly into the program, with the following DAO implementing two methods:
Update method: Perform additions and deletions and change operations
queryForList method: Perform a query operation
Params: Any number of arrays, configured in SQL? Placeholder
PackageCom.david;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.jdbc.core.JdbcTemplate;Importorg.springframework.stereotype.Repository;Importjava.util.List; @Repository Public classHellodao {@Autowired jdbctemplate jdbctemplate; Public intUpdate () {String SQL= "Update user set username =?" where UserID =? "; Object[] Params=Newobject[]{"Boot", 1}; returnjdbctemplate.update (Sql,params); } PublicList queryForList () {String SQL= "SELECT * from User"; returnjdbctemplate.queryforlist (SQL); }}
Helloservice.java
Spring boot also automatically configures the transaction, adding an annotation directly to the service.
PackageCom.david;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.stereotype.Service;Importorg.springframework.transaction.annotation.Transactional;Importjava.util.List; @Transactional//Open transaction @service Public classHelloService {@AutowiredPrivateHellodao DAO; Public intUpdate () {returndao.update (); } PublicList queryForList () {returndao.queryforlist (); }}
Hellocontroller.java
PackageCom.david;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.web.bind.annotation.*; @RestController Public classHellocontroller {@AutowiredPrivateHelloService Service; @GetMapping ("/update") PublicString Update () {service.update (); return"Update"; } @GetMapping ("/list") PublicString list () {service.queryforlist (); return"List"; }}
Spring Boot jdbctemplate Access database (6)