-
Notifications
You must be signed in to change notification settings - Fork 0
4.JdbcTemplate
337547038 edited this page Nov 7, 2023
·
1 revision
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
新建一个类,如UserController.java
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.Map;
import java.util.List;
@RestController
public class UserController {
@Autowired
JdbcTemplate jdbcTemplate;
@RequestMapping("/list")
public String hello() {
String sql = "select * from user";
List<Map<String, Object>> list_maps = jdbcTemplate.queryForList(sql);
System.out.println(list_maps);
return list_maps.toString();
}
}找不到org.springframework.jdbc.core.JdbcTemplate时,可在pom.xml中添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>使用JdbcTemplate的好处:
- 简洁明了:使用JdbcTemplate的queryForList方法可以直接执行SQL查询,无需编写额外的控制层代码,使代码更加简洁和易于理解。
- 减少开发时间:由于省略了编写控制层的步骤,可以加快开发速度,减少开发时间。
- 灵活性强:可以直接编写SQL语句,灵活性更高,能够处理更复杂的查询需求。
使用JdbcTemplate不好的地方:
- 缺乏封装性:直接在Java代码中执行SQL查询,缺乏封装性,不利于代码的管理和维护。
- 安全性问题:直接在代码中编写SQL语句,容易暴露数据库的敏感信息,存在一定的安全隐患。
- 难以调试:直接在代码中执行SQL查询,当出现错误时,难以确定是代码问题还是数据库问题,增加了调试的难度。
- 数据库依赖性强:直接在代码中执行SQL查询,使代码与特定数据库的依赖性增强,不利于系统的可移植性。
综上所述,使用JdbcTemplate的queryForList方法直接执行SQL查询可以简化代码和提高开发速度,但需要注意安全性、封装性和可维护性等方面的问题。在实际开发中,建议根据具体需求和项目要求权衡利弊,谨慎使用。