Spring ~ JdbcTemplate。

Spring ~ JdbcTemplate。



JdbcTemplate 作用。

简化。

使用。

Maven。


    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

    </dependencies>

入门案例。
package com.geek.jdbcTmplate;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

/**
 * JdbcTemplateDemo01 最基本用法。
 */
public class JdbcTemplateDemo00 {

    public static void main(String[] args) {

        // 准备数据源。(Spring 内置数据源)。
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        driverManagerDataSource.setUrl("jdbc:mysql://192.168.223.128/geek_spring_dbutils");
        driverManagerDataSource.setUsername("root");
        driverManagerDataSource.setPassword("root");

        // 创建 JdbcTemplate 对象。
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        // 给 jdbcTemplate 设置数据源。
        jdbcTemplate.setDataSource(driverManagerDataSource);

        // 执行操作。
        jdbcTemplate.execute("insert into account (name, money) values ('ccc', '1000')");
    }

}



Spring IoC。

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 http://www.springframework.org/schema/beans/spring-beans.xsd">

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

    <!-- 数据源。-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://192.168.223.128/geek_spring_dbutils"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

</beans>

package com.geek.jdbcTmplate;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * JdbcTemplateDemo01 IoC。
 */
public class JdbcTemplateDemo01 {

    public static void main(String[] args) {

        // 获取容器。
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:bean.xml");

        // 获取对象。
        JdbcTemplate jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");

        // 执行操作。
        jdbcTemplate.execute("insert into account (name, money) values ('ddd', '1000')");
    }

}



CRUD。
package com.geek.jdbcTmplate;

import com.geek.domain.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * JdbcTemplate CRUD 操作。
 */
public class JdbcTemplateCRUD {

    public static void main(String[] args) {

        // 获取容器。
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:bean.xml");

        // 获取对象。
        JdbcTemplate jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");

        // 增。
//        jdbcTemplate.execute("insert into account (name, money) values ('eee', '1000')");
//        jdbcTemplate.update("insert into account (name, money) values (?, ?)", "eee", 333f);

        // 删。
//        jdbcTemplate.update("delete from account where name = ?", "geek");

        // 改。
//        jdbcTemplate.update("update account set name = ?, money = ? where id = ?",
//                "geek", 7000f, 9);

        // 查。
//        List<Account> accountList = jdbcTemplate.query("select * from account where money < ?", new AccountRowMapper(), 10000F);
        // Spring 提供的封装实现。
        List<Account> accountList = jdbcTemplate.query("select * from account where money < ?", new BeanPropertyRowMapper<Account>(Account.class), 10000F);
        for (Account account : accountList) {
            System.out.println(account);
        }
        // Spring 的 JdbcTemplate 靠不同的 query(); 方法实现返回。
        // dbutils 靠 ResultSetHandler 中的返回值商定返回的内容。

        // 查询一个。
        List<Account> accountList1 = jdbcTemplate.query("select * from account where id = ?", new BeanPropertyRowMapper<>(Account.class), 1);
        System.out.println(accountList1.isEmpty() ? "没有内容" : accountList1.get(0));

        // 查询返回一行一列(使用聚合函数,但不加 group by 子句)。
        Integer integer = jdbcTemplate.queryForObject("select count(*) from account where money < ?", Integer.class, 10000F);
        System.out.println("integer = " + integer);
    }

}

/**
 * 定义 Account 的封装策略。
 */
class AccountRowMapper implements RowMapper<Account> {
    /**
     * 把结果集中的数据封装到 Account 中,然后由 Spring 把每个 Account 加入到集合中。
     *
     * @param resultSet
     * @param i
     * @return
     * @throws SQLException
     */
    @Override
    public Account mapRow(ResultSet resultSet, int i) throws SQLException {
        Account account = new Account();
        account.setId(resultSet.getInt("id"));
        account.setName(resultSet.getString("name"));
        account.setMoney(resultSet.getFloat("money"));
        return account;
//        return null;
    }

}

在这里插入图片描述



JdbcTemplate 在 dao 中的使用。
package com.geek.dao.impl;

import com.geek.dao.IAccountDao;
import com.geek.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

/**
 * 账户的持久层实现类。
 */
public class AccountDaoImpl implements IAccountDao {

    private JdbcTemplate jdbcTemplate;

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

    /**
     * 根据 id 查询账户。
     *
     * @param accountId
     * @return
     */
    @Override
    public Account findAccountById(Integer accountId) {
        List<Account> accountList = jdbcTemplate.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), accountId);
        return accountList.isEmpty() ? null : accountList.get(0);
    }

    /**
     * 根据 name 查询账户。
     *
     * @param name
     * @return
     */
    @Override
    public Account findAccountByName(String name) {
        List<Account> accountList = jdbcTemplate.query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), name);
        if (accountList.isEmpty()) {
            return null;
        }
        if (accountList.size() > 1) {
            throw new RuntimeException("结果集不唯一。");
        }
        return accountList.get(0);
    }

    /**
     * 修改账户。
     *
     * @param account
     */
    @Override
    public void updateAccount(Account account) {
        int update = jdbcTemplate.update("update account set name = ?, money = ? where id = ?", account.getName(), account.getMoney(), account.getId());
    }

}

    <!-- 配置账户持久层。-->
    <bean id="accountDao" class="com.geek.dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
package com.geek.jdbcTmplate;

import com.geek.dao.IAccountDao;
import com.geek.domain.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * JdbcTemplateDemo01 IoC。
 */
public class JdbcTemplateDemo04 {

    public static void main(String[] args) {

        // 获取容器。
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:bean.xml");

        // 获取对象。
        IAccountDao accountDao = applicationContext.getBean("accountDao", IAccountDao.class);

        // 执行操作。
        Account account = accountDao.findAccountById(1);

        System.out.println("account = " + account);
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

lyfGeek

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

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

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

打赏作者

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

抵扣说明:

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

余额充值