spring简化了对jdbc操作的难度,能够更简单的使用JDBC,避免样板式代码。
CRUD
pom
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.3.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
我的DAO层
package com.imikasa.dao;
import com.imikasa.pojo.Hero;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Repository
public class HeroDao implements HeroDaoInterface {
private JdbcTemplate jdbcTemplate;
@Autowired
public HeroDao(JdbcTemplate jdbc){
this.jdbcTemplate = jdbc;
}
@Override
public List<Hero> findAll() {
List<Hero> all = jdbcTemplate.query("select * from hero", new RowMapper<Hero>() {
@Override
public Hero mapRow(ResultSet resultSet, int i) throws SQLException {
Hero hero = new Hero(resultSet.getInt("id"),resultSet.getString("name"),resultSet.getInt("hp"));
return hero;
}
});
return all;
}
@Override
public Hero findById(int id) {
Hero hero = jdbcTemplate.queryForObject("select * from hero where id = ?", new RowMapper<Hero>() {
@Override
public Hero mapRow(ResultSet resultSet, int i) throws SQLException {
return new Hero(resultSet.getInt("id"), resultSet.getString("name"), resultSet.getInt("hp"));
}
},id);
return hero;
}
@Override
public int add(Hero hero) {
int update = jdbcTemplate.update("insert into hero (name,hp) values (?,?)", hero.getName(), hero.getHp());
return update;
}
@Override
public int delete(int id) {
int update = jdbcTemplate.update("delete from hero where id = ?", id);
return update;
}
@Override
public int update(Hero hero) {
int update = jdbcTemplate.update("update hero set name = ?,hp = ? where id = ?", hero.getName(), hero.getHp(), hero.getId());
return update;
}
}
仅供参考……
网友评论