导入依赖
在 pom.xml
中添加对 JdbcTemplate
的依赖:
<!-- Spring JDBC 的依赖包,使用 spring-boot-starter-jdbc 或 spring-boot-starter-data-jpa 将会自动获得HikariCP依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- MYSQL包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
连接数据库
在application.properties
中添加如下配置:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot2?serverTimezone=GMT%2B8
spring.datasource.password=root
spring.datasource.username=root
为什么要在url后面加?serverTimezone=GMT%2B8,可以参考:https://blog.csdn.net/love20yh/article/details/80799610
具体编码
创建一张 t_user
的表:
CREATE TABLE `t_user` (
`id` int(8) NOT NULL AUTO_INCREMENT COMMENT '主键自增',
`username` varchar(50) NOT NULL COMMENT '用户名',
`password` varchar(50) NOT NULL COMMENT '密码',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表';
实体类:
public class User {
private Long id;
private String username;
private String password;
// TODO 省略get set
}
restful 风格接口:
import com.lg.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class SpringJdbcController {
private final JdbcTemplate jdbcTemplate;
@Autowired
public SpringJdbcController(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@GetMapping
public List<User> queryUsers() {
// 查询所有用户
String sql = "select * from t_user";
return jdbcTemplate.query(sql, new Object[]{}, new BeanPropertyRowMapper<>(User.class));
}
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
// 根据主键ID查询
String sql = "select * from t_user where id = ?";
return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(User.class));
}
@DeleteMapping("/{id}")
public int delUser(@PathVariable Long id) {
// 根据主键ID删除用户信息
String sql = "DELETE FROM t_user WHERE id = ?";
return jdbcTemplate.update(sql, id);
}
@PostMapping
public int addUser(@RequestBody User user) {
// 添加用户
String sql = "insert into t_user(username, password) values(?, ?)";
return jdbcTemplate.update(sql, user.getUsername(), user.getPassword());
}
@PutMapping("/{id}")
public int editUser(@PathVariable Long id, @RequestBody User user) {
// 根据主键ID修改用户信息
String sql = "UPDATE t_user SET username = ? ,password = ? WHERE id = ?";
return jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), id);
}
}
测试接口
创建单元测试LiugaoApplicationTests
,通过TestRestTemplate
模拟GET
、POST
、PUT
、DELETE
等请求操作:
import com.lg.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(classes =LiugaoApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class LiugaoApplicationTests {
private static final Logger log = LoggerFactory.getLogger(LiugaoApplicationTests.class);
@Autowired
private TestRestTemplate template;
@LocalServerPort
private int port;
@Test
public void test1() throws Exception {
template.postForEntity("http://localhost:" + port + "/users", new User("user1", "pass1"), Integer.class);
log.info("[添加用户成功]\n");
// TODO 如果是返回的集合,要用 exchange 而不是 getForEntity ,后者需要自己强转类型
ResponseEntity<List<User>> response2 = template.exchange("http://localhost:" + port + "/users", HttpMethod.GET, null, new ParameterizedTypeReference<List<User>>() {
});
final List<User> body = response2.getBody();
log.info("[查询所有] - [{}]\n", body);
Long userId = body.get(0).getId();
ResponseEntity<User> response3 = template.getForEntity("http://localhost:" + port + "/users/{id}", User.class, userId);
log.info("[主键查询] - [{}]\n", response3.getBody());
template.put("http://localhost:" + port + "/users/{id}", new User("user11", "pass11"), userId);
log.info("[修改用户成功]\n");
template.delete("http://localhost:" + port + "/users/{id}", userId);
log.info("[删除用户成功]");
}
}
然后我们在浏览器测试一下查询所有用户的接口,测试结果如下: