1、前言java
springboot整合JdbcTemplate。在此記錄下,分享給你們。mysql
2、springboot整合JdbcTemplateweb
一、pom文件 依賴引入spring
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.8.RELEASE</version> </parent> <dependencies> <!-- SpringBoot 整合 jdbc --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- mysql 驅動 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!-- SpringBoot 測試 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- SpringBoot web組件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
二、 application.yml 新增配置sql
spring: datasource: url: jdbc:mysql://localhost:3306/yys_springboot_jdbc username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver
三、UserController.java數據庫
/** * 用戶管理 * Controller * @author yys */ @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping("/add") public String addUser(String userName, Integer age) { return userService.addUser(userName, age) ? "success" : "fail"; } }
四、UserService.javaspringboot
/** * 用戶管理 * Service * @author yys */ @Service public class UserService { @Autowired private JdbcTemplate jdbcTemplate; public boolean addUser(String userName, Integer age) { return jdbcTemplate.update("insert into yys_user values(null, ?, ?, 1, now(), now());", userName, age) > 0 ? true : false; } }
五、啓動類app
@SpringBootApplication public class YysApp { public static void main(String[] args) { SpringApplication.run(YysApp.class, args); } }
六、初始化sql文件spring-boot
CREATE TABLE `yys_user` ( `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT 'ID,自增列', `user_name` varchar(32) NOT NULL COMMENT '用戶名', `age` int(11) NOT NULL COMMENT '用戶年齡', `status` tinyint(2) NOT NULL DEFAULT '1' COMMENT '狀態:-1-刪除;1-正常;', `create_time` datetime NOT NULL COMMENT '建立時間', `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時間', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
七、測試測試
http://localhost:8080/user/add?userName=yys&age=18
a、頁面結果 - 以下圖所示 :
b、數據庫結果 - 以下圖所示 :