spring-boot-starter-jdbc 是 Spring Boot 提供的一个用于简化 JDBC 操作的启动器。使用这个启动器,你可以快速配置和使用 JDBC 进行数据库操作。以下是一个详细指南,介绍如何在 Spring Boot 项目中使用 spring-boot-starter-jdbc。
1.添加依赖项:
在 pom.xml(如果使用 Maven)中添加以下依赖项:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> </dependencies>
2. 配置数据库连接
在 application.properties
或 application.yml
文件中配置数据库连接信息。以下是 application.properties
的示例配置(以 MySQL 为例):
spring: datasource: username: root password: root url: jdbc:mysql://192.168.56.102:3306/boot-test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC driver-class-name: com.mysql.cj.jdbc.Driver
3.创建表信息
CREATE TABLE `sys_user` ( `id` int NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `age` int DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
4. 创建数据模型
定义你的实体类。例如,一个简单的用户实体类 SysUser
:
public class SysUser { private Integer id; private String name; private int age; // Getters and setters }
5. 创建 Repository
使用 JdbcTemplate
进行数据库操作。首先,创建一个 UserRepository
类:
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class SysUserRepository { private final JdbcTemplate jdbcTemplate; @Autowired public SysUserRepository(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } private final RowMapper<SysUser> rowMapper = (rs, rowNum) -> { SysUser user = new SysUser(); user.setId(rs.getInt("id")); user.setName(rs.getString("name")); user.setAge(rs.getInt("age")); return user; }; public List<SysUser> findAll(){ return jdbcTemplate.query("SELECT * FROM SYS_USER",rowMapper); } public int save(SysUser user){ return jdbcTemplate.update("INSERT INTO SYS_USER (name, age) VALUES (?, ?)",user.getName(),user.getAge()); } //其他增删改查信息 }
6.测试,创建TestController
@RestController public class TestController { private final SysUserRepository sysUserRepository; @Autowired public TestController(SysUserRepository sysUserRepository) { this.sysUserRepository = sysUserRepository; } @GetMapping("/getUsers") public List<SysUser> getAllUser(){ return sysUserRepository.findAll(); } @GetMapping("/addUser") public int addUser(@RequestParam("name") String name, @RequestParam("age") int age){ SysUser sysUser = new SysUser(); sysUser.setName(name); sysUser.setAge(age); return sysUserRepository.save(sysUser); } }
启动项目,访问 http://localhost:8080/addUser?name=zhangsan&age=22,http://localhost:8080/addUser?name=lisi&age=25新增zhangsan和lisi两个用户
再次访问http://localhost:8080/getUsers,观察返回
[ { "id": 1, "name": "zhangsan", "age": 22 }, { "id": 2, "name": "lisi", "age": 25 } ]