Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Spring operation of the database in Jdbc did a deeper package, and convenient tool for database operations JdbcTemplate Spring is provided. We can help JdbcTemplate to perform all database operations, such as insert, update, delete, and retrieve data from the database, and effectively avoid direct use of tedious coding Jdbc brings.
JdbcTemplate provides the following five types of methods:
method | DEFINITIONS |
---|---|
execute | It can be used to execute any SQL statement, typically used to execute DDL statements |
update | For performing add, modify and delete statements |
batchUpdate | For executing batch related statements |
query and queryForXXX | Statement for executing queries related |
call | To execute database stored procedures and functions related statements |
1, rely on the introduction of JDBC
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>2.0.6</version>
</dependency>
2、Java Bean
Lombok is used, it is by way of annotation, the compiler automatically generates attribute constructors, getter / setter, equals, hashcode, toString method.
@Data
public class Blog {
private Integer blog;
private Integer fans;
private Integer likes;
private Integer comments;
private Integer pageview;
private Integer integral;
private Integer ranking;
private Date createTime;
}
3, BlogController
@RestController
public class JdbcTest {
@Resource
private JdbcTemplate jdbcTemplate;
@GetMapping("insertBlog")
public int insertBlog(Blog blog){
String sql = "insert into blog(blog,fans,likes,comments,pageview,integral,ranking,create_time) values(?,?,?,?,?,?,?,?)";
return jdbcTemplate.update(sql, blog.getBlog(), blog.getFans(), blog.getLikes(), blog.getComments(), blog.getPageview(), blog.getIntegral(), blog.getRanking(),blog.getCreateTime());
}
}
4, application.yml
#配置数据源
spring:
datasource:
url: jdbc:mysql://localhost:3306/testdb?characterEncoding=utf8
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver