Spring 04 JdbcTemplate

6 篇文章 0 订阅

JdbcTemplate概述

JdbcTemplate是Spring框架中提供的一个对象,对原始的JDBC API进行简单封装,其用法与DBUtils`类似.

JdbcTemplate配置

<!--配置JDBCTemplate-->
<bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource">
    </property>
</bean>
<!--配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver">
    </property>
    <property name="url" value="jdbc:mysql://localhost:3306/eesy">
    </property>
    <property name="username" value="root">
    </property>
    <property name="password" value="root">
    </property>
</bean>

JdbcTemplate 实现增删改

public static void main(String[] args) {
    //1 获取容器
   ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
   JdbcTemplate jt=ac.getBean("JdbcTemplate",JdbcTemplate.class);
   jt.execute("insert into account(name,money)values('eeee',1000)");
   //保存
   jt.update("insert into account(name,money) values(?,?)","eeee",333);
   //更新
   jt.update("update account set name=?,money=? where id=?","eeee",4567,7);
   //删除
   jt.update("delect from account where id=?",8);

JdbcTemplate 实现查询

与DBUtils十分类似,JdbcTemplate的查询操作使用其query()方法,其参数如下:

  • ​ String sql: SQL语句

  • ​ RowMapper rowMapper: 指定如何将查询结果ResultSet对象转换为T对象.

  • ​ @Nullable Object… args: SQL语句的参数

其中RowMapper类类似于DBUtils的ResultSetHandler类,可以自己写一个实现类,但常用Spring框架内置的实现类BeanPropertyRowMapper(T.class)

//自己写的类AccountRoMapper()
//List<Account> accounts=jt.query("select * from account where money=?",new AccountRoMapper(),1000f);
//查询所有
List<Account> accounts=jt.query("select * from account where money=?",new BeanPropertyRowMapper<Account>(Account.class),1000f);
for(Account account:accounts){
    System.out.println(account);
}
//查询一个
public Account findAccountById(Integer accountId) {
    List<Account> accounts = jdbcTemplate.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), accountId);
    return accounts.isEmpty() ? null : accounts.get(0);
}
class AccountRoMapper implements RowMapper<Account>{
    /*把结果集中的数据封装到Account
     */
    @Override
    public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
        Account account =new Account();
        account.setId(rs.getInt("id"));
        account.setName(rs.getString("name"));
        account.setMoney(rs.getFloat("money"));
        return account;
    }

聚合查询

JdbcTemplate中执行聚合查询的方法为queryForObject()方法,其参数如下:

  • String sql: SQL语句
  • Class<T> requiredType: 返回类型的字节码
  • @Nullable Object... args: SQL语句的参数
public static void main(String[] args) {
    //1.获取Spring容器
    ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    //2.根据id获取JdbcTemplate对象
    JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
    //3.聚合查询
    Integer total = jt.queryForObject("select count(*) from account where money > ?", Integer.class, 500);
    System.out.println(total);
}

在DAO层使用JdbcTemplate

在每个DAO层直接加入JdbcTemplate的话,如果要有很多个DAO,那么每个里面都需要加,那样代码就会变得冗余。为了抽取代码,我们可以建立一个JdbcDaoSupport类用于抽取重复代码。然后再DAO的实现类中继承。在JdbcDaoSupport类中定义了JdbcTemplateDataSource成员属性,在实际编程中,只需要向其注入DataSource成员即可,DataSource的set方法中会注入JdbcTemplate对象.

public class JdbcDaoSupport {
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

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

    private JdbcTemplate jdbcTemplate;
    private DataSource dataSource;

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource=dataSource;
        if(jdbcTemplate==null){
            jdbcTemplate=creteJdbcTemplate(dataSource);
        }
    }
    public JdbcTemplate creteJdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
}

目前Spring中有内置的JdbcDaoSupport,所以我们可以不写具体的类,直接继承Spring中的类

在实现DAO接口时,我们通过super.getJdbcTemplate()方法获得JdbcTemplate对象.

@Override
public Account findAccountById(Integer accountid) {
    List<Account> accounts=super.getJdbcTemplate().query("select * from account where id=?",new BeanPropertyRowMapper<Account>(Account.class),accountid);
    return accounts.isEmpty()?null:accounts.get(0);
}

@Override
public Account findAccountByName(String accountName) {
    List<Account> accounts=super.getJdbcTemplate().query("select * from account where name=?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
    if(accounts.isEmpty()){
        return null;
    }
    if(accounts.size()>1){
        throw new RuntimeException("结果集不唯一");
    }
    return accounts.get(0);
}

@Override
public void updateAccount(Account account) {
    super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值