天天看点

SpringBoot默认持久层操作工具JDBC Template

作者:长颈鹿睡觉

在SpringBoot中目前流行的持久层操作工具是Mybatis Plus。

Mybatis Plus 使用参考:SpringBoot整合Mybatis-Plus

但是在SpringBoot中还内置了一款持久层操作工具JDBC Template,它比Mybatis Plus操作上更加繁琐,不建议使用。

但是在有的老项目上还在使用,有需要的可以了解一下。

引入Starter

在SpringBoot的pom文件中引入JDBC Template的Starter。

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>           

配置数据源参数

在application.properties中配置数据库连接参数。

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/baex
spring.datasource.username=root
spring.datasource.password=rootroot           

注入JDBCTemplate对象

在需要使用持久化操作的地方通过@Autowired注解注入JDBC Template对象。

@Autowired
    JdbcTemplate jdbcTemplate;           

查询数据

使用JDBC Template对象的query对象查询数据库,传入要执行的SQL语句和RowMapper对象。

String sql = "select role_id, role_name from sys_role";
List<Role> result = jdbcTemplate.query(sql, rowMapper);           

RowMapper是将查询结果封装到实体类中,需要自己实现封装的操作。

如下是将查询结果封装到Role实体类中,其实就是用set方法将字段值设置到Role的对象中。

RowMapper<Role> rowMapper = new RowMapper<Role>() {
            @Override
            public Role mapRow(ResultSet rs, int rowNum) throws SQLException {
                Role role = new Role();
                role.setRoleId(rs.getInt("role_id"));
                role.setRoleName(rs.getString("role_name"));
                return role;
            }
        };           

更新和删除相对更简单一点,通过update方法执行对应的SQL就可以。

完整代码

@SpringBootTest
public class JDBCT {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Test
    void testJDBC(){
        String sql = "select role_id, role_name from sys_role";

        RowMapper<Role> rowMapper = new RowMapper<Role>() {
            @Override
            public Role mapRow(ResultSet rs, int rowNum) throws SQLException {
                Role role = new Role();
                role.setRoleId(rs.getInt("role_id"));
                role.setRoleName(rs.getString("role_name"));
                return role;
            }
        };

        List<Role> result = jdbcTemplate.query(sql, rowMapper);
        System.out.println(result);
    }
}           

其他配置

在applcation.properties中还提供了JDBC Template的配置项可供选择。

# 一次fetch操作获取的数据行数
spring.jdbc.template.fetch-size=-1
# 查询最大行数
spring.jdbc.template.max-rows=1000
# 超时时间,默认单位是秒
spring.jdbc.template.query-timeout=100000