spring中的JdbcTemplate的使用方法

在没有使用mybatis框架之前,通常是用原始的方法编写持久层代码,但即便有jdbcutil工具类,开发效率也非常的低,那么spring为我们提供了JdbcTemplate类,能快速的开发持久层的代码,它位于spring-jdbc模块中,和DB-util中的queryrunner有异曲同工之妙。

第一步,获取JdbcTemplate对象
想要使用JdbcTemplate对象,首先要进行获取,获取它有两种方式,一种是通过编写JDBC工具类来获取,第二种方法是通过spring工厂管理它,然后在获取,实现了IOC

第一种方式,JDBC工具类获取(不推荐)

JdbcUtil类

public class JdbcUtil {

    private static String url = "jdbc:mysql://localhost:3306/mybatis?useUnicode=true&useSSL=false&characterEncoding=utf-8&serverTimezone=UTC";
    private static String user = "root";
    private static String password = "root";
    private static DriverManagerDataSource dataSource;

    static{
        dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
    }

    public static JdbcTemplate getJdbcTemplate(){
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate;
    }

    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        try {
            if (connection!=null) connection.close();
            if (statement!=null) statement.close();
            if (resultSet!=null) resultSet.close();
            System.out.println("资源关闭成功");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}

使用传统的工具类将datasource注入到JdbcTemplate对象中,这样他就能获取到connection了,这里使用了线程池技术,用到了spring-jdbc包中的DriverManagerDataSource线程池,这样就成功的配置了JdbcTemplate对象了

第二种方式,使用spring进行配置和管理(推荐)

可以在spring的xml文件中配置

    <context:property-placeholder location="classpath:db.properties" />

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>

也可以自己在创建配置文件,用java代码注入JdbcTemplate到spring中
需要在spring配置文件中开启注解扫描

    <!--包扫描所有的@component标识,并把他们注册到spring工厂中,变成bean-->
    <beans>
        <context:component-scan base-package="com.chinasoft.spring.*"/>
    </beans>

然后编写DataSourcesConfig类

@Configuration
public class DataConfig {

    @Bean
    public JdbcTemplate getJdbcTemplate(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/mybatis?useUnicode=true&useSSL=false&characterEncoding=utf-8&serverTimezone=UTC");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }
}

第二步,在实现类中注入JdbcTemplate对象
通过上面的配置,已经可以很轻松的获取到JdbcTemplate对象了,通常在持久层dao层使用此对象

在xxxDaoImpl中获取JdbcTemplate对象的方式
如果使用了第一种方式配置,那么需要使用如下方式

private JdbcTemplate template = JdbcUtil.getJdbcTemplate();

使用使用了spring来管理JdbcTemplate对象,则用如下方式

@Autowired
private JdbcTemplate template;

第三步,在实现类中使用JdbcTemplate对象

@Repository
public class AccountDaoImpl implements AccountDao {


    @Autowired
    @Qualifier("getJdbcTemplate")
    private JdbcTemplate template;

    @Override
    public List<Account> findAll() {
        /**
         *  query: 执行查询, 如何返回是  多个 实体类, 就使用这个方法
         *  sql: sql 语句
         *  RowMapper 的实现类
         */
        //final List<Account> list = template.query("select * from account", new AccountRowMap());
        final List<Account> list = template.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
        return list;
    }

    @Override
    public Account findById(Integer id) {
        // 取得 一行对象
        final Account account = template.queryForObject(
                "select * from account where id = ?",
                // 就是将 resultSet 对象 转换为 泛型的实体类
                new BeanPropertyRowMapper<Account>(Account.class), id);
        return account;
    }

    @Override
    public Account findByName(String name) {
        // 取得 一行对象
        final Account account = template.queryForObject(
                "select * from account where name = ?",
                // 就是将 resultSet 对象 转换为 泛型的实体类
                new BeanPropertyRowMapper<Account>(Account.class), name);
        return account;
    }

    @Override
    public int update(Account account) {
        // 影响数据库的行数
        int ret = template.update("update account set name = ? , money = ? where id = ?",
                account.getName(), account.getMoney(), account.getId());
        return ret;
    }

    @Override
    public int insert(Account account) {
        int ret = template.update("insert into  account ( name, money) value( ?, ?)",
                account.getName(), account.getMoney());
        return ret;
    }

    @Override
    public Long count() {
        final Long count = template.queryForObject("select count(*) from account", Long.class);
        return count;
    }

}

可以看到,JdbcTemplate对象封装了许多方法,能快速的开发持久层代码,可以注意到查询方法是需要一个BeanPropertyRowMapper对象的,这个对象的作用是帮助我们将查询出来的数据封装成对象返回给我们,这是很重要的。

最后RowMapper对象是可以被重写的,可以进行自定义,同样也可以实现查询的功能

public class AccountRowMap implements RowMapper<Account> {
    /**
     * @param rs :  resultSet
     * @param rowNum the number of the current row
     * @return   Account 实例化对象
     * @throws SQLException if an SQLException is encountered getting
     *                      column values (that is, there's no need to catch SQLException)
     */
    @Override
    public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
        final Account account = new Account();
        account.setId(rs.getInt("id"));
        account.setMoney(rs.getFloat("money"));
        account.setName(rs.getString("name"));
        return account;
    }
}

可以看到它实现了RowMapper的接口,如果项目不用mybatis做持久层的话,那么这样就能在项目中很好的使用JdbcTemplate对象来完成持久层的开发了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值