Spring中的JdbcTemplate进行数据库操作

JdbcTemplate概述

JdbcTemplate是Spring框架中提供的一个对象,对原始的JDBC API进行简单封装,其用法与DBUtils类似.
项目开始前的操作(增加相应的依赖)

<dependency>
			     <groupId>org.springframework.boot</groupId>
			     <artifactId>spring-boot</artifactId>
			     <version>2.2.1.RELEASE</version>
			</dependency>
			//jbdc的依赖
			<dependency>
			     <groupId>org.springframework</groupId>
			     <artifactId>spring-jdbc</artifactId>
			     <version>5.0.2.RELEASE</version>
			</dependency>
			<dependency>
			     <groupId>org.springframework</groupId>
			     <artifactId>spring-tx</artifactId>
			</dependency>
			//数据库的依赖
			<dependency>
			     <groupId>mysql</groupId>
			     <artifactId>mysql-connector-java</artifactId>
			     <version>5.1.6</version>
			</dependency>

JdbcTemplate对象的创建

<bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSourcr"></property>
 </bean>

pom.xml中配置数据库

配置数据源: 与DBUtils中的QueryRunner对象类似,JdbcTemplate对象在执行sql语句时也需要一个数据源,这个数据源可以使用C3P0或者DBCP,也可以使用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自带的数据源

使用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实现增删改(account表示数据库名)

与DBUtils十分类似,JdbcTemplate的增删改操作使用其update(“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.执行增加操作
        jt.update("insert into account(name,money)values(?,?)","名字",5000);
    }

删除操作

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

更新操作

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

使用JdbcTemplate实现查询

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

String sql: SQL语句
RowMapper<T> rowMapper: 指定如何将查询结果ResultSet对象转换为T对象.
@Nullable Object... args: SQL语句的参数

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

查询所有:

public List<Account> findAllAccounts() {
    List<Account> accounts = jdbcTemplate.query("select * from account ", new BeanPropertyRowMapper<Account>(Account.class));
    return accounts;
}

查询所有姓名相同的。

public List<Account> findAllAccounts(String name) {
    List<Account> accounts = jdbcTemplate.query("select * from account where name=? ", new BeanPropertyRowMapper<Account>(Account.class)),name;
    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);
}

//根据name查询

List<Account> account=jt.query("select * from 数据库名 where name=?",new BeanPropertyRowMapper<Account>(Account.class),"sds");
	if(account.isEmpty()){//判断是否为空
		return null;
	}
	if(account.size()>1){
		throw new RuntimeException("结果集不唯一")
		}
		return account.get(0)
	account.isEmpty()?"没有内容":accounts.get(0);
聚合查询:
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层使用JdbcTemplate,需要给DAO注入JdbcTemplate对象.

public class AccountDaoImpl implements IAccountDao {
    
    private JdbcTemplate jdbcTemplate;	// JdbcTemplate对象

    // JdbcTemplate对象的set方法
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    // DAO层方法
    @Override
    public Account findAccountById(Integer id) {
        // 实现...
    }

    // DAO层方法
    @Override
    public Account findAccountByName(String name) {
        // 实现...
    }

    // 其它DAO层方法...
}

DAO层对象继承JdbcDaoSupport类

在实际项目中,我们会创建许多DAO对象,若每个DAO对象都注入一个JdbcTemplate对象,会造成代码冗余.

实际的项目中我们可以让DAO对象继承Spring内置的JdbcDaoSupport类.在JdbcDaoSupport类中定义了JdbcTemplate和DataSource成员属性,在实际编程中,只需要向其注入DataSource成员即可,DataSource的set方法中会注入JdbcTemplate对象.
DAO的实现类中调用父类的getJdbcTemplate()方法获得JdbcTemplate()对象.

JdbcDaoSupport类的源代码如下:

public abstract class JdbcDaoSupport extends DaoSupport {
    
    @Nullable
    private JdbcTemplate jdbcTemplate;	// 定义JdbcTemplate成员变量

    public JdbcDaoSupport() {
    }

    // DataSource的set方法,注入DataSource时调用createJdbcTemplate方法注入JdbcTemplate
    public final void setDataSource(DataSource dataSource) {
        if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) {
            this.jdbcTemplate = this.createJdbcTemplate(dataSource);
            this.initTemplateConfig();
        }
    }

    // 创建JdbcTemplate,用来被setDataSource()调用注入JdbcTemplate
    protected JdbcTemplate createJdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    // JdbcTemplate的get方法,子类通过该方法获得JdbcTemplate对象
    @Nullable
    public final JdbcTemplate getJdbcTemplate() {
        return this.jdbcTemplate;
    }

    @Nullable
    public final DataSource getDataSource() {
        return this.jdbcTemplate != null ? this.jdbcTemplate.getDataSource() : null;
    }

    public final void setJdbcTemplate(@Nullable JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
        this.initTemplateConfig();
    }

    // ...
}

在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对象.

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类的源代码,DAO层的配置就只能基于xml配置,而不再可以基于注解配置了.
————————————————
版权声明:本文为CSDN博主「ncepu_Chen」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/ncepu_Chen/article/details/94566610

发布了10 篇原创文章 · 获赞 0 · 访问量 223

猜你喜欢

转载自blog.csdn.net/yunqiu21/article/details/103873343