文章目录
1. JdbcTemplate的概述
它是 spring 框架中提供的一个对象,是对原始 Jdbc API 对象的简单封装。
Spring 框架为我们提供了很多 的操作模板类。
- 操作关系型数据的: JdbcTemplate HibernateTemplate
- 操作 nosql 数据库的: RedisTemplate
- 操作消息队列的: JmsTemplate
持久层总图:
2. JdbcTemplate的作用
用于和数据库操作,实现对表的CRUD操作
3. 初步创建和使用JdbcTemplate
1.创建maven工程 day04_eesy_01jdbctemplate
2.在配置文件pom.xml中添加依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itheima</groupId>
<artifactId>day04_eesy_01jdbctemplate</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
</dependencies>
</project>
3.创建数据库表account(可以直接使用上个案例中的数据库表)
数据库表截图:
4.创建数据库表account对应实体类Account.java
/**
* 账户的实体类
*/
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
5.创建JdbcTemplate.java, 实现JdbcTemplate的基本用法
/**
* JdbcTemplate的最基本用法
*/
public class JdbcTemplateDemo1 {
public static void main(String[] args) {
//准备数据源,spring的内置数据源
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/eesy");
driverManagerDataSource.setUsername("root");
driverManagerDataSource.setPassword("123456");
//1.创建对象
JdbcTemplate jdbcTemplate = new JdbcTemplate();
//给jdbcTemplate设置数据源
jdbcTemplate.setDataSource(driverManagerDataSource);
//2.执行操作
jdbcTemplate.execute("insert into account(name ,money)values ('ccc',1000)");
}
}
6.运行后数据库变为:
由于常见数据库的时候设置id为自增长,上个案例中进行过记录删除的操作,因此增加的记录的id直接从 7 开始
7.目录结构
4. JdbcTemplate在Spring的IOC中使用
1.在resources目录下创建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"></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://localhost:3306/eesy"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
</beans>
2.创建JdbcTemplateDemo2.java, 通过获取容器的方式获取 JdbcTemplate对象
/**
* JdbcTemplate的最基本用法
*/
public class JdbcTemplateDemo2 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate",JdbcTemplate.class);
jdbcTemplate.execute("insert into account(name ,money)values ('ccc',1000)");
}
}
3.运行结果
5. JdbcTemplate的CRUD操作
创建JdbcTemplateDemo3.java类用于执行JdbcTemplate的CRUD操作
5.1 保存
/**
* JdbcTemplate的CRUD操作
*/
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate",JdbcTemplate.class);
//保存
jdbcTemplate.update("insert into account(name,money)values (?,?)","ddd","1000");
}
}
5.2 更新
/**
* JdbcTemplate的CRUD操作
*/
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate",JdbcTemplate.class);
//更新
jdbcTemplate.update("update account set name = ?,money=? where id = ?","test","500",7);
}
}
5.4 删除
/**
* JdbcTemplate的CRUD操作
*/
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate",JdbcTemplate.class);
//删除
jdbcTemplate.update("delete from account where id=?",8);
}
}
5.5 查询所有
1.方法定位
2.进行查询
/**
* JdbcTemplate的CRUD操作
*/
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate",JdbcTemplate.class);
//查询所有
List<Account> accounts = jdbcTemplate.query("select * from account where money > ?",new AccountRowMapper(),500f);
for (Account account : accounts){
System.out.println(account);
}
}
}
/**
* 定义Account的封装策略
*/
class AccountRowMapper implements RowMapper<Account>{
/**
* 把结果集中的数据封装到Account中,然后由Spring把m每个Account加到集合中
* @param resultSet
* @param i
* @return
* @throws SQLException
*/
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 ;
}
}
运行结果:
3.使用Spring提供的RowMapper实现(new BeanPropertyRowMapper(Account.class) )进行查询
/**
* JdbcTemplate的CRUD操作
*/
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate",JdbcTemplate.class);
//3.执行操作
//jdbcTemplate.execute("insert into account(name ,money)values ('ccc',1000)");
//保存
// jdbcTemplate.update("insert into account(name,money)values (?,?)","ddd","1000");
//更新
//jdbcTemplate.update("update account set name = ?,money=? where id = ?","test","500",7);
//删除
// jdbcTemplate.update("delete from account where id=?",8);
//查询所有
// List<Account> accounts = jdbcTemplate.query("select * from account where money > ?",new AccountRowMapper(),500f);
List<Account> accounts = jdbcTemplate.query("select * from account where money>?", new BeanPropertyRowMapper<Account>(Account.class),500f);
for (Account account : accounts){
System.out.println(account);
}
}
}
运行结果:
5.6 查询一个
/**
* JdbcTemplate的CRUD操作
*/
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate",JdbcTemplate.class);
//查询一个
List<Account> accounts = jdbcTemplate.query("select * from account where id>?", new BeanPropertyRowMapper<Account>(Account.class),7);
System.out.println(accounts.isEmpty()?"没有内容":accounts.get(0));
//
}
}
运行结果:
5.7 查询返回一行一列
要求: 使用聚合函数,但不加 group by语句
/**
* JdbcTemplate的CRUD操作
*/
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate",JdbcTemplate.class);
//查询返回一行一列(使用聚合函数,但不加group by语句)
Long count = jdbcTemplate.queryForObject("select count(*) from account where money>?",Long.class,500f);
System.out.println(count);
}
}
运行结果:
6. JdbcTemplate在Dao中的使用
1.创建账户的持久层接口 IAccountDao.java
/**
* 账户的持久层接口
*/
public interface IAccountDao {
/**
* 根据id查询账户
* @param accountId
* @return
*/
Account findAccountById(Integer accountId);
/**
* 根据名称查询账户
* @param accountName
* @return
*/
Account findAccountByName(String accountName);
/**
* 更新账户
* @param account
*/
void updateAccount(Account account);
}
2.创建账户的持久层实现类AccountDaoImpl.java
public class AccountDaoImpl implements IAccountDao {
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 id=?",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());
}
}
3.在配置文件 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">
<!--配置账户的持久层-->
<bean id="accountDao" class="com.itheima.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.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/eesy"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
</beans>
4.创建JdbcTemplateDemo4.java类,并在其中完成测试
查询
/**
* JdbcTemplate的最基本用法
*/
public class JdbcTemplateDemo4 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
IAccountDao accountDao=applicationContext.getBean("accountDao",IAccountDao.class);
Account account = accountDao.findAccountById(2);
System.out.println(account);
}
}
运行结果:
更新:
/**
* JdbcTemplate的最基本用法
*/
public class JdbcTemplateDemo4 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
IAccountDao accountDao=applicationContext.getBean("accountDao",IAccountDao.class);
Account account = accountDao.findAccountById(2);
account.setMoney(500f);
accountDao.updateAccount(account);
// System.out.println(account);
}
}
运行结果:
7. JdbcTemplateSupport的使用
使用目的: 解决在持久层的实现类中重复定义 JdbcTemplateSupport的问题
1.创建JdbcTemplateSupport.java类
/**
* 此类用于抽取Dao中的重复代码
*/
public class JdbcDaoSupport {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setDataSource(DataSource dataSource){
if(jdbcTemplate == null){
jdbcTemplate = createJdbcTemplate(dataSource);
}
}
private JdbcTemplate createJdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
}
说明:
添加createDataSource方法,并在该方法中完成JdbcTemplate的初始化,
即表示如果在配置文件中没有对JdbcTemplate进行注入,此时JdbcTemplate为null,
在对 dataSource进行注入的时候会调用 setDataSource,完成对JdbcTemplate的初始化
2.使持久层实现类 AccountServiceImpl直接继承JdbcTemplateSupport,并删除关于JdbcTemplate的定义
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
public Account findAccountById(Integer accountId) {
List<Account> accounts = super.getJdbcTemplate().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 = super.getJdbcTemplate().query("select * from account where id=?",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) {
super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
说明: 使用JdbcTemplate的时候直接调用 super.getJdbcTemplate() 方法即可
3.在配置文件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">
<!--配置账户的持久层-->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
<!--<property name="jdbcTemplate" ref="jdbcTemplate"></property>-->
<property name="dataSource" ref="dataSource"></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.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/eesy"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
</beans>
说明:取消对JdbcTemplate的配置, 直接使用 DataSource
4.在 JdbcTemplateDemo4.java中进行测试
/**
* JdbcTemplate的最基本用法
*/
public class JdbcTemplateDemo4 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
IAccountDao accountDao=applicationContext.getBean("accountDao",IAccountDao.class);
Account account = accountDao.findAccountById(2);
account.setMoney(3000f);
accountDao.updateAccount(account);
// System.out.println(account);
}
}
5.运行结果
8. 使用Spring框架提供的JdbcTemplateSupport
Spring框架中提供了JdbcTemplateSupport, 因此可以直接使用Spring提供的JdbcTemplateSupport
1.删除在上个步骤中创建的JdbcTemplateSupport.java类
2.此时会发现 AccountServiceImpl继承JdbcTemplateSupport, 并且未报错
原因: 自动导入了Spring框架提供的JdbcTemplate
3.在JdbcTemplateDemo4.java中测试
/**
* JdbcTemplate的最基本用法
*/
public class JdbcTemplateDemo4 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
IAccountDao accountDao=applicationContext.getBean("accountDao",IAccountDao.class);
Account account = accountDao.findAccountById(2);
// account.setMoney(3000f);
// accountDao.updateAccount(account);
System.out.println(account);
}
}
4.运行结果
9. 总结Dao的编写方式
第一种:
直接在持久层实现类中定义JdbcTemplate
public class AccountDaoImpl2 implements IAccountDao {
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 id=?",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());
}
}
第二种:
自己创建JdbcTemplateSupport.java类,然后让持久层实现类继承它
这种方法就是上述 7中所用方法
第三种:
使用Spring框架提供的JdbcTemplateSupport
这种方法就是上述8中所用方法
总结:
第一种和第二种方式可用于 XML和和注解配置
第三种直接使用Spring提供的JdbcTemplate方式适用于XML配置, 在注解配置中使用有一定的困难
原因: Spring提供的JdbcTemplate为jar包, 不方便添加注解