SpringBoot学习笔记(十)——Spring Boot整合JdbcTemplate

在pom.xml文件中增加如下依赖:

<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
       <groupId>mysql</groupId>
       <artifactId>mysql-connector-java</artifactId>
</dependency>
配置Datasource,只要按照这个名字设置值,那么Springboot会将application.properties中的对应值自动设置到数据源里。
application.properties代码如下:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/example
spring.datasource.username=root
spring.datasource.password=root
使⽤JdbcTemplate,Service类中代码如下:
@Service
public class UserService {

    @Autowired
    private MyProperties myProperties;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public String test() {
        return myProperties.getXingming()+","+myProperties.getPassword();
    }

    public String testJdbc() {
        jdbcTemplate.execute("insert into example.books values(4,'spring',25,'女里学习')");
        return "success";
    }
}

controller类中代码如下:

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private TestService testService;

    @RequestMapping("/")
    String home() {
        return userService.test();
    }

    @RequestMapping("/profiles")
    String testProfiles() {
        return testService.testProfiles();
    }

    @RequestMapping("/jdbc")
    String testJdbc() {
        return userService.testJdbc();
    }
}
posted @ 2022-09-15 23:10  一直学习的程序小白  阅读(41)  评论(0编辑  收藏  举报