Spring(四)-- JdbcTemplate

JdbcTemplate

  • 实现 jdbctemplate 要导入的依赖
<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.17</version>
        </dependency>
  • bean.xml的配置
<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--配置账户的持久层-->
    <bean id="accountDao" class="com.oym.dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>

    <!--配置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.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/eesy?useUnicode=true
        &amp;characterEncoding=UTF-8&amp;useSSL=false&amp;serverTimezone=Asia/Shanghai&amp;
        zeroDateTimeBehavior=CONVERT_TO_NULL"></property>
        <property name="username" value="root"></property>
        <property name="password" value="666666"></property>
    </bean>
</beans>

  • 非IOC模式下的jdbc代码:
//准备数据源:spring的内置数据源
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        ds.setUrl("jdbc:mysql://127.0.0.1:3306/eesy?useUnicode=true&" +
                "characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai" +
                "&zeroDateTimeBehavior=CONVERT_TO_NULL");
        ds.setUsername("root");
        ds.setPassword("666666");
        //1.创建jdbcTemplate对象
        JdbcTemplate jt = new JdbcTemplate();
        //给jt设置数据源;
        jt.setDataSource(ds);
        //2.执行操作
        jt.execute("insert into account(name,money) values('eee',5000)");
  • 调用 bean.xml 后的用法001:
public class JdbcTemplatDemo3 {

    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(?,?)","kkk",5555f);
        //更新
       jt.update("update account set name=?,money=? where id=?","bai",5555f,"6");
        //删除
        jt.update("delete from account where id=?",8);
        //查询所有
        List<Account> accounts = jt.query("select * from account where money > ?",new BeanPropertyRowMapper<Account>(Account.class),2000f);
       for (Account account : accounts) {
           System.out.println(account);        
       }
        //查询一个
        List<Account> accounts2 = jt.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),1);
        System.out.println(accounts2.isEmpty()?"没有内容":accounts.get(0));
        //查询返回一行一列 (使用聚合函数,但不加group by子句)
        int count = jt.queryForObject("select count(*) from account where money > ?",Integer.class,1000f);
        System.out.println(count);
    }
}

/*
* 定义Account的封装策略*/
class AccountRowMapper implements RowMapper<Account>{

    public Account mapRow(ResultSet resultSet, int i) throws SQLException {
        return null;
    }
}
  • 持久层实现代码:
*
* 账户的持久层实现类*/
public class AccountDaoImpl implements AccountDao {

    private JdbcTemplate jdbcTemplate;

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

    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);
    }

    public Account findAccountByName(String accountName) {
        List<Account> accounts = jdbcTemplate.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);
    }

    public void updateAccount(Account account) {
        jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
    }
}
  • 调用代码块002:
*
* JdbcTemplate的最基本用法*/
public class JdbcTemplatDemo4 {

    public static void main(String[] args) {

        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.获取对象
        AccountDao accountDao = ac.getBean("accountDao",AccountDao.class);

        Account account = accountDao.findAccountById(1);
        System.out.println(account);

        account.setMoney(10000f);
        accountDao.updateAccount(account);
    }
}
发布了58 篇原创文章 · 获赞 7 · 访问量 9268

猜你喜欢

转载自blog.csdn.net/Mr_OO/article/details/100852227