步骤1 添加依赖
<!--jdbc模板-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--中间件-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
步骤2 全局配置数据源信息
application.yml
spring:
# 数据源的配置
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
步骤3 使用JdbcTemplate
// 继承jdbcDaoSupport 或者 JdbcTemplate 都是可以的
@Repository
public class BookDaoImpl extends JdbcTemplate implements BookDao {
// JdbcTemplate设置这里的内置数据源字段
@Autowired
public void setMyDataSource(DataSource dataSource) {
setDataSource(dataSource);
}
@Override
public List<Book> findAll() {
String sql = "select * from book";
List<Book> books = query(sql, new RowMapper<Book>() {
// 设置 列名与Bean属性段的对应
@Override
public Book mapRow(ResultSet rs, int rowNum) throws SQLException {
Book book = new Book();
book.setId((Integer) rs.getObject("id"));
book.setName((String) rs.getObject("name"));
book.setAuthor((String) rs.getObject("author"));
return book;
}
});
return books;
}
}