1.引入maven依赖
<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.properties配置文件中配置JDBC属性
#数据库jdbc连接url地址,serverTimezone设置数据库时区东八区 spring.datasource.url=jdbc:mysql://localhost:3306/springboot-001?serverTimezone=GMT%2B8 #数据库账号 spring.datasource.username=root #数据库密码 spring.datasource.password=123 #指定数据库驱动 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
通过以上两部就已经完成了JDBC和SpringBoot的配置,就可以通过依赖注入的方式使用JdbcTemplate
@Service public class UserDao { //SpringBoot提供的数据库操作类 @Autowired JdbcTemplate jdbcTemplate; public List<User> getUserList() { return jdbcTemplate.query("select * from users", new BeanPropertyRowMapper(User.class)); } public void createUser(User user) { jdbcTemplate.update("insert into users(name,age)values(?,?)",user.getName(),user.getAge()); } public User getUser(Long id) { final User user = new User(); jdbcTemplate.query("select * from users where id="+id,new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { user.setId(id); user.setName(rs.getString("name")); user.setAge(rs.getInt("age")); } }); return user; } public void updateUser(Long id, User user) { jdbcTemplate.update("update users set name=?,age=? where id=?",user.getName(),user.getAge(),id); } public void deleteUser(Long id) { jdbcTemplate.update("delete from users where id=?",id); } }