springboot整合使用JdbcTemplate

zhangsan分享之家發表於2020-12-26
  • 資料庫訪問

4.1springboot整合使用JdbcTemplate

4.1.1 pom檔案引入

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.1.8.RELEASE </version>

</parent>

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-jdbc</artifactId>

</dependency>

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>5.1.21</version>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

</dependencies>

4.1.2 application.yml新增配置

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

 

4.1.3 UserService

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Boolean inserUser(String name, Integer age) {
        int update = jdbcTemplate.update("insert into users values(null,?,?);", name, age);
        return update > 0 ? true : false;
    }
}

 

4.1.4 App

@ComponentScan(basePackages = "com.mayikt")

@EnableAutoConfiguration

public class App {

public static void main(String[] args) {

SpringApplication.run(App.class, args);

}

}

 

4.1.5資料庫表結構

CREATE TABLE `users` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `name` varchar(32) NOT NULL COMMENT '使用者名稱稱',

  `age` int(11) DEFAULT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

1.B站線上學習地址:https://www.bilibili.com/video/BV1Q64y1f7fX 

2. 百度雲盤視訊和文件下載:

連結:https://pan.baidu.com/s/15wAcEczic7I5MvhUizIJkg

提取碼:1234

3.springboot 修訂版本文件和程式碼下載

連結:http://note.youdao.com/noteshare?id=74244e05cc0bc189dbb8873ccfce55cb

相關文章