学习笔记_Spring_day04

数据库操作模板JdbcTemplate和事务控制

数据库操作模板JdbcTemplate

JdbcTemplate概述
JdbcTemplate是Spring框架中提供的一个对象,对原始的JDBC API进行简单封装,其用法与DBUtils类似.
JdbcTemplate对象的创建
使用Spring内置的数据源DriverManagerDataSource,需要在bean.xml中配置如下:

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

        <!--配置DataSource-->
        <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/day17"></property>
            <property name="username" value="root"></property>
            <property name="password" value="root"></property>
        </bean>

JdbcTemplate的增删改查操作

实现增删改
JdbcTemplateDemo类:

public static void main(String[] args) {
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.获取对象
        JdbcTemplate jt =ac.getBean("jdbcTemplate",JdbcTemplate.class);
        //3.执行操作
        //保存操作
        //jt.update("insert into account(name,money)values(?,?)","名字",5000);
        //更新操作
        //jt.update("update account set money = money-? where id = ?",300,6);
        //删除操作
        //jt.update("delete from account where id = ?",6);
        }}

查询

 //1.查询所有
 List<Account> accounts = jt.query("select * from account where money > ?",
            new BeanPropertyRowMapper<Account>(Account.class),1000f);
     for (Account account : accounts) {
         System.out.println(account);
     }
     //2.查询一个
     List<Account> accounts = jt.query("select * from account where id = ?",
             new BeanPropertyRowMapper<Account>(Account.class),1);
     System.out.println(accounts.isEmpty()?"无内容":accounts.get(0));
     //3.聚合查询
      Long count = jt.queryForObject("select count(*) from account where money > ?",Long.class,1000f);
     System.out.println(count);

在DAO使用JdbcTemplate

1.第一种方式
在DAO中定义jdbctemplate
注入jdbctemplate

  <!--配置账户的持久层-->
        <bean id="accountDao" class="com.itheima.dao.impl.IAccountDaoImpl">
          <property name="jdbcTemplate" ref="jdbcTemplate"></property>
        </bean>
<!--配置jdbcTemplate-->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSource"></property>
        </bean>

实现类

//账户的持久层实现类
public class AccountDaoImpl implements IAccountDao {
    private JdbcTemplate jdbcTemplate;	// JdbcTemplate对象

    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值