JdbcTemplate 概述:
它是 spring 框架中提供的一个对象,是对原始 Jdbc API 对象的简单封装。spring 框架为我们提供了很多的操作模板类。
操作关系型数据的:
JdbcTemplate
HibernateTemplate
操作 nosql 数据库的:
RedisTemplate
操作消息队列的:
JmsTemplate
JdbcTemplate 在 spring-jdbc-x.x.x.RELEASE.jar 中,在导包的时候,除了要导入这个 jar 包外,
还需要导入一个 spring-tx-5.0.2.RELEASE.jar(它是和事务相关的)。
JdbcTemplate 对象的创建:
源码:
public JdbcTemplate() { } public JdbcTemplate(DataSource dataSource) { setDataSource(dataSource); afterPropertiesSet(); } public JdbcTemplate(DataSource dataSource, boolean lazyInit) { setDataSource(dataSource); setLazyInit(lazyInit); afterPropertiesSet(); }
除了默认构造函数之外,都需要提供一个数据源。既然有set方法,那么就可以使用依赖注入,可以在配置文件中配置这些对象。
编写 spring 的配置文件:
<?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"> <!-- 配置数据源,使用spring提供的内置数据源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driverClass}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> </beans>
将数据库连接的信息配置到属性文件中:
【定义属性文件】
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring
jdbc.username=root
jdbc.password=root
【引入外部的属性文件】
一种方式:
<!-- 引入外部属性文件: --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"/> </bean> <!--<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <array> <value>classpath:jdbc.properties</value> <value>......</value>
...... </array> </property> </bean>-->
另一种方式:
<context:property-placeholder location="classpath:jdbc.properties"/>
JdbcTemplate 的增删改查操作:
在使用之前需要导入坐标
<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> <version>5.0.2.RELEASE</version> </dependency>
在 spring 配置文件中配置 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"> <!-- 配置一个数据库的操作模板: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.jdbc.Driver"></property> <property name="url" value="jdbc:mysql:///spring"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> </beans>
保存操作
public class JdbcTemplateDemo3 { public static void main(String[] args) { //1.获取 Spring 容器 ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); //2.根据 id 获取 bean 对象 JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate"); //3.执行操作 //保存 jt.update("insert into account(name,money)values(?,?)","fff",5000); } }
更新操作
jt.update("update account set money = money-? where id = ?",300,6);
删除操作
jt.update("delete from account where id = ?",6);
查询所有操作
List<Account> accounts = jt.query("select * from account where money > ? ", new BeanPropertyRowMapper<Account>(Account.class), 500);
查询一个操作
List<Account> accounts = jt.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), 1); System.out.println(accounts.isEmpty()?"没有内容":accounts.get(0));
查询返回一行一列操作
Integer total = jt.queryForObject("select count(*) from account where money > ? ",Integer.class, 500);
在 dao 中使用 JdbcTemplate
第一种方式:在 dao 中定义 JdbcTemplate,在配置文件中注入数据源
/** * 此版本的 dao ,需要给 dao 注入 JdbcTemplate */ public class AccountDaoImpl implements IAccountDao { private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } }
第二种方式:让 dao 继承 JdbcDaoSupport
JdbcDaoSupport 是 spring 框架为我们提供的一个类,该类中定义了一个 JdbcTemplate 对象,
可以直接获取使用,但是要想创建该对象,需要为其提供一个数据源,具体源码如下:
public abstract class JdbcDaoSupport extends DaoSupport { //定义对象 private JdbcTemplate jdbcTemplate; //set 方法注入数据源,判断是否注入了,注入了就创建 JdbcTemplate public final void setDataSource(DataSource dataSource) { if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) { //如果提供了数据源就创建 JdbcTemplate this.jdbcTemplate = createJdbcTemplate(dataSource); initTemplateConfig(); } } //使用数据源创建 JdcbTemplate protected JdbcTemplate createJdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); } //当然,我们也可以通过注入 JdbcTemplate 对象 public final void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; initTemplateConfig(); } //使用 getJdbcTmeplate 方法获取操作模板对象 public final JdbcTemplate getJdbcTemplate() { return this.jdbcTemplate; }
在 dao 中使用:
/** * 此版本 dao,只需要给它的父类注入一个数据源 */ public class AccountDaoImpl2 extends JdbcDaoSupport implements IAccountDao { @Override public void updateAccount(Account account) { //getJdbcTemplate()方法是从父类上继承下来的。 getJdbcTemplate().update("update account set money = ? where id = ?", account.getMoney(), account.getId()); } }
在配置文件中注入数据源
<bean id="accountDao2" class="com.fgy.dao.impl.AccountDaoImpl2"> <!-- 注入 dataSource --> <property name="dataSource" ref="dataSource"></property> </bean>
两版 Dao 区别
第一种在 Dao 类中定义 JdbcTemplate 的方式,适用于所有配置方式(xml 和注解都可以)。
第二种让 Dao 继承 JdbcDaoSupport 的方式,只能用于基于 XML 的方式,注解用不了。