SpringBoot整合JDBC


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);
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM