📅  最后修改于: 2023-12-03 14:47:33.561000             🧑  作者: Mango
Spring JDBC 是 Spring 框架提供的一套 JDBC 操作模板。它简化了 JDBC 的模板代码,从而减少了因 JdbcTemplate 样板代码而引起的重复错误,提高了代码的可读性和可维护性。Spring JDBC 还提供了一种称为“DAO 模式”的模式,用于访问数据库,并将数据访问代码与业务逻辑代码分离。
引入 Spring JDBC 的依赖:
<!-- Spring JDBC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>{版本号}</version>
</dependency>
创建数据源对象:
@Configuration
public class JdbcConfig {
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Value("${jdbc.driverClassName}")
private String driverClassName;
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
}
创建 JdbcTemplate 对象:
@Component
public class UserDao {
private JdbcTemplate jdbcTemplate;
public UserDao(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
执行 SQL 命令:
public class UserDao {
// ...
public List<User> list() {
return jdbcTemplate.query("SELECT * FROM user", new BeanPropertyRowMapper<>(User.class));
}
public User get(Long id) {
return jdbcTemplate.queryForObject("SELECT * FROM user WHERE id = ?", new BeanPropertyRowMapper<>(User.class), id);
}
public void save(User user) {
jdbcTemplate.update("INSERT INTO user (username, password) VALUES (?, ?)", user.getUsername(), user.getPassword());
}
public void update(User user) {
jdbcTemplate.update("UPDATE user SET username = ?, password = ? WHERE id = ?", user.getUsername(), user.getPassword(), user.getId());
}
public void delete(Long id) {
jdbcTemplate.update("DELETE FROM user WHERE id = ?", id);
}
}
使用 DAO 模式访问数据库:
public interface UserDao {
List<User> list();
User get(Long id);
void save(User user);
void update(User user);
void delete(Long id);
}
@Repository
public class JdbcUserDao implements UserDao {
private JdbcTemplate jdbcTemplate;
public JdbcUserDao(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public List<User> list() {
return jdbcTemplate.query("SELECT * FROM user", new BeanPropertyRowMapper<>(User.class));
}
@Override
public User get(Long id) {
return jdbcTemplate.queryForObject("SELECT * FROM user WHERE id = ?", new BeanPropertyRowMapper<>(User.class), id);
}
@Override
public void save(User user) {
jdbcTemplate.update("INSERT INTO user (username, password) VALUES (?, ?)", user.getUsername(), user.getPassword());
}
@Override
public void update(User user) {
jdbcTemplate.update("UPDATE user SET username = ?, password = ? WHERE id = ?", user.getUsername(), user.getPassword(), user.getId());
}
@Override
public void delete(Long id) {
jdbcTemplate.update("DELETE FROM user WHERE id = ?", id);
}
}
Spring JDBC 是 Spring 框架提供的一套 JDBC 操作模板。可以大大简化 JDBC 的样板代码,提高代码的可读性和可维护性,同时支持声明式事务管理和 DAO 模式。Spring JDBC 的学习曲线较陡峭,但是它为企业级应用程序提供了一套强大的、可扩展的数据访问方案。