JavaWeb框架 - Spring03

JdbcTemplate: 数据库操作模板【会用即可】

  1. 概述:
    • 概念: spring 框架中提供的一个对象,是对原始 Jdbc API 对象的简单封装 其用法与DBUtils类似
    • 对象创建的方式:三种
      public JdbcTemplate() {
      }
      public JdbcTemplate(DataSource dataSource) {
      	setDataSource(dataSource);
      	afterPropertiesSet();
      }
      public JdbcTemplate(DataSource dataSource, boolean lazyInit) {
      	setDataSource(dataSource);
      	setLazyInit(lazyInit);
      	afterPropertiesSet();
      }
      
    • 对象创建的步骤:
      • 配置数据源: 与DBUtils中的QueryRunner对象类似,JdbcTemplate对象在执行sql语句时也需要一个 数据源, 这个数据源可以使用C3P0或者Druid,也可以使用Spring的内置数据源DriverManagerDataSource等等

        • 配置C3P0数据源:

          使用C3P0数据源,需要在bean.xml中配置如下:

          <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
              <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
              <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/数据库名"></property>
              <property name="user" value="用户名"></property>
              <property name="password" value="密码"></property>
          </bean>
          
        • 配置DBCP数据源

          使用DBCP数据源,需要在bean.xml中配置如下:

          <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
          	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
              <property name="url" value="jdbc:mysql://localhost:3306/数据库名"></property>
              <property name="username" value="用户名"></property>
              <property name="password" value="密码"></property>
          </bean>
          
        • 使用Spring内置的数据源DriverManagerDataSource

          在bean.xml中配置如下:

          <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/数据库名"></property>
              <property name="username" value="用户名"></property>
              <property name="password" value="密码"></property>
          </bean>
          
      • 创建JdbcTemplate对象:

        • 向JdbcTemplate中注入数据源创建对象,在bean.xml中配置如下:

          <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
              <property name="dataSource" ref="dataSource"></property>
          </bean>
          
  2. 使用JdbcTemplate 进行 CRUD的操作:使用非常的简单
    • JdbcTemplate的增删改操作使用其update("SQL语句", 参数...)方法
      • C 增加:

        public static void main(String[] args) {
            //1.获取Spring容器
            ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
            //2.根据id获取JdbcTemplate对象
            JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
            //3.执行增加操作
            jt.update("insert into account(name,money)values(?,?)","张三",5000);
        }
        
      • U 更新:

        public static void main(String[] args) {
        	//1.获取Spring容器
            ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
            //2.根据id获取JdbcTemplate对象
            JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
            //3.执行更新操作
        	jt.update("update account set money = money-? where id = ?",300,6);
        }
        
      • D 删除 :

        public static void main(String[] args) {
            //1.获取Spring容器
            ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
            //2.根据id获取JdbcTemplate对象
            JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
            //3.执行删除操作
            jt.update("delete from account where id = ?",6);
        }			
        
    • JdbcTemplate的查询操作使用其query(SQL语句, rowMapper对象, SQL语句的参数)方法
      • 方法中的参数:
        • RowMapper<T> rowMapper: 指定如何将查询结果ResultSet对象转换为T对象 一般不用手动的实现 使用的是BeanPropertyRowMapper 传入要封装类型的字节码文件
      • R 查询:
        • 查询所有:
          public List<Account> findAllAccounts() {
              List<Account> accounts = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
              return accounts;
          }
          
        • 通过id进行查询:
           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);
          }
          
        • 聚合查询:使用的方法是queryForObject
          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);
          }				
          
  3. JdbcDaoSupport类的使用:
    • 上一种方式存在的问题:多个dao对象存在着重复的代码 会在成代码的冗余,使用JdbcDaoSupport类将重复的代码进行抽取
    • 解决问题的方式:实际的项目中我们可以让dao对象继承Spring内置的JdbcDaoSupport类.在JdbcDaoSupport类中定义了JdbcTemplate和DataSource成员属性,在实际编程中,只需要向其注入DataSource成员即可,DataSource的set方法中会注入JdbcTemplate对象
      • 在bean.xml中,我们只要为dao对象注入DataSource对象即可,让JdbcDaoSupport自动调用JdbcTemplate的set方法注入JdbcTemplate
        <?xml version="1.0" encoding="UTF-8"?>
        <beans xmlns="http://www.springframework.org/schema/beans"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd">
        	<!-- 配置数据源-->
            <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/数据库名"></property>
                <property name="username" value="用户名"></property>
                <property name="password" value="密码"></property>
            </bean>
            <!-- 配置账户的持久层-->
            <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
                <!--不用我们手动配置JdbcTemplate成员了-->
                <!--<property name="jdbcTemplate" ref="jdbcTemplate"></property>-->
                <property name="dataSource" ref="dataSource"></property>
            </bean>
        </beans> 
        
      • dao接口中,不需定义JdbcTemplate成员变量,只需定义并实现dao层方法即可.
        public interface IAccountDao {
        	// 根据id查询账户信息
        	Account findAccountById(Integer id);	
        	// 根据名称查询账户信息
        	Account findAccountByName(String name);
        	// 更新账户信息
        	void updateAccount(Account account);
        }
        
      • 实现dao接口时, 通过super.getJdbcTemplate()方法获得JdbcTemplate对象. 需要继承JdbcDaoSupport 这个类
        public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
           
           @Override
           public Account findAccountById(Integer id) {
        	//调用继承自父类的getJdbcTemplate()方法获得JdbcTemplate对象
               List<Account> list = getJdbcTemplate().query("select * from account whereid = ? ", new AccountRowMapper(), id);
               return list.isEmpty() ? null : list.get(0);
           }
        
           @Override
           public Account findAccountByName(String name) {
               //调用继承自父类的getJdbcTemplate()方法获得JdbcTemplate对象
               List<Account> accounts = getJdbcTemplate().query("select * from account wherename = ? ", new BeanPropertyRowMapper<Account>(Account.class), name);
               if (accounts.isEmpty()) {
                   return null;
               } else if (accounts.size() > 1) {
                   throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
               }
               return accounts.get(0);
           }
        
           @Override
           public void updateAccount(Account account) {
        	//调用继承自父类的getJdbcTemplate()方法获得JdbcTemplate对象
               getJdbcTemplate().update("update account set money = ? where id = ? ", account.getMoney(), account.getId());
           }
        }
        
    • 这样的方式存在的问题:
      JdbcDaoSupport类的源代码是第三方的(Spring中内置的),dao层的配置就只能只能基于xml配置,而不能使用基于注解配置
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

上山打卤面

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值