JdbcTemplate是Spring框架自带的对JDBC操作的封装,目的是提供统一的模板方法使对数据库的操作更加方便、友好,效率也不错。

整合使用JdbcTemplate实现对图书的添加功能小案例

采用springboot2.0.0版本

1.导入所需依赖jar包

<!--web应用-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <!--单测-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <!--jdbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency> <!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

2.application.properties中的配置

1 spring.datasource.url=jdbc:mysql://localhost:3306/bookshop
2 spring.datasource.username=root
3 spring.datasource.password=123
4 spring.datasource.driver-class-name=com.mysql.jdbc.Driver

3.entity层

 @Entity(name = "book") public class Book {
@Id
@GeneratedValue
private Integer bookid;
@Column
private String bookname;
@Column
private Integer bookprice; get set方法省略。。
}

4.service层

 @Service
public class BookService {
@Autowired
private JdbcTemplate jdbcTemplate;
public void createUser(Integer booid,String bookname,Integer bookprice){
System.out.println("createUser");
jdbcTemplate.update("insert into book values(?,?,?);",booid,bookname,bookprice);
System.out.println("图书添加成功!!");
} }

5.controller层

 @Controller
public class BookController {
@Autowired
private BookService userService; @RequestMapping("/createUser")
public String createUser(Integer booid,String bookname,Integer bookprice){
userService.createUser(booid,bookname,bookprice);
return "success";
}
}

6.success.ftl

 <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1>success</h1>
</body>
</html>

7.启动项目

SpringBoot整合使用JdbcTemplate-LMLPHP

控制台打印

SpringBoot整合使用JdbcTemplate-LMLPHP

04-20 19:11