Spring boot 使用JdbcTemplate操作数据库

相较于java Web项目,Spring boot框架提供了DataSource和JdbcTemplate来进行数据库操作。
依赖

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-jdbcartifactId>
        dependency>
         
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.0.2version>
        dependency>

application.yml中配置datasource的bean

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/schoolActivity?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=GMT%2B8 #url
    username: root #账号
    password: 1234 #密码
    driver-class-name: com.mysql.cj.jdbc.Driver #driver class
    type: com.alibaba.druid.pool.DruidDataSource

使用自动装配获得bean
在用@Component(或@Service、@Repository、@Controller)(这些注解放在实现类上而不是接口上)注解的类中

@Repository
public class UserDaoImpl implements UserDao {

    JdbcTemplate jdbcTemplate;
    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}

使用
jdbcTemplate方法
执行条语句 execute
执行更新语句 update
查询 query
查询时使用RowMapper将查询结果的一行映射成实体对象

    RowMapper<User> rowMapper=new RowMapper() {
        @Override
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            long id = rs.getLong("id");
            String name = rs.getString("name");
            String password = rs.getString("password");
            String email = rs.getString("email");
            String type=rs.getString("type");
            User user=new User(id,name,email,password,type);
            return user;
        }
    };

要查询的结果包含多条记录,要得到实体类对象的列表时,使用query方法进行查询,而不用queryForMap、queryForList或queryForObject

    public List<User> list(int from, int len) {
        String sql="select * from user limit ?, ?";
        Object[] paras = {from,len};
        int[] types = new int[]{Types.INTEGER,Types.INTEGER};
        List<User> users = jdbcTemplate.query(sql, paras, types, rowMapper);
        return users;
    }

你可能感兴趣的:(数据库,java,spring,boot,java,数据库)