如果对此文感兴趣,可以继续看下一篇博文,持续更新,新手学习,有问题欢迎指正:
https://blog.csdn.net/renjingjingya0429/article/details/90241005
一、Spring中的JdbcTemplate
1.1 JdbcTemplate概述
它是Spring框架中提供的一个对象,是对原始Jdbc API对象的简单封装。Spring框架为我们提供了很多的操作类模板。
操作关系型数据库的:
- JdbcTemplate
- HibernateTemplate
操作nosql数据库的:
- RedisTemplate
操作消息队列的:
- JmsTemplate
1.2 Spring 中配置数据源
(1)导入jar包。
(2)编写Spring 的配置文件。
(3)配置数据源(我们使用的是 Spring 内置的数据源)。
①配置c3p0数据源
导入c3p0的jar包。在 Spring 的配置文件中配置:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///spring_day02"></property>
<property name="user" value="root"></property>
</bean>
②配置dbcp数据源
导入dbcp的jar包。在 Spring 的配置文件中配置:
<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:// /spring_day02"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>
③配置Spring内置的数据源
Spring 框架也为我们提供了一个内置的数据源,在spring-jdbc-5.0.2.REEASE.jar 包中:
配置如下:
<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_day02"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>
(4)将数据库连接的信息配置到属性文件中。
【定义属性文件】
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_day02
jdbc.username=root
jdbc.password=123
【引入外部的属性文件】
一种方式:
<!-- 引入外部属性文件: -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"/>
</bean>
另一种方式:
<context:property-placeholder location="classpath:jdbc.properties"/>
1.3 JdbcTemplate的CRUD操作
(1)前期准备
创建数据库:
create database spring_day02;
use spring_day02;
创建表:
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;
(2)在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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->
<!--配置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 name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
</beans>
(3)CRUD操作
/**
* JDBCTemplate入门用法
*/
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取jdbcTemplate对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.执行操作
//(1)保存
jt.update("insert into account(name,money) values('杨霞',100)");
//(2)更新
// jt.update("update account set money = ? where name = ?",222,"save");
//(3)删除
// jt.update("delete from account where name = ?","save");
//(4)查询所有
// List<Account> Accounts = jt.query("select * from account where name=?", new BeanPropertyRowMapper<Account>(Account.class),"任静");
// for (Account account : Accounts) {
// System.out.println(account);
// }
//(5)查询一个
List<Account> Accounts1 = jt.query("select * from account where name=?", new AccountRowMapper(), "任静");
System.out.println(Accounts1.isEmpty() ? "没有结果" : Accounts1.get(0));
// (6)查询返回一行一列:聚合函数的使用(queryForObject()是Spring3.x的新方法)
Integer count1 = jt.queryForObject("select count(*) from account where money>?", Integer.class, "50");
Long count2 = jt.queryForObject("select count(*) from account where money>?", Long.class, "50");
System.out.println(count1);
System.out.println(count2);
}
}
class AccountRowMapper implements RowMapper<Account> {
@Override
public Account mapRow(ResultSet rs, int i) throws SQLException {
Account account = new Account();
account.setName(rs.getString("name"));
account.setMoney(rs.getFloat("money"));
return account;
}
}
1.4 在dao中使用JdbcTemplate
1.4.1 实体类
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 +
'}';
}
}
1.4.2 第一种方式:在dao中定义JdbcTemplate(此种方式适合使用注解的方式来配置JdbcTemplate)
/**
* 账户的接口
*/
public interface IAccountDao {
/**
* 根据id查询账户信息
*/
public Account findAccountById(Integer id);
/**
* 根据名称查询账户信息
*/
public Account findAccountByName(String name);
/**
* 更新账户信息
*/
public void updateAccount(Account account);
}
//此种方式适合使用注解的方式来配置JdbcTemplate
/**
* 账户的持久层实现类
* 需要给dao注入JdbcTemplate
*/
public class AccountDaoImpl implements IAccountDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public Account findAccountById(Integer id) {
List<Account> accounts = jdbcTemplate.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), id);
return accounts.isEmpty()?null:accounts.get(0);
}
@Override
public Account findAccountByName(String name) {
List<Account> accounts = jdbcTemplate.query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), name);
if (accounts.isEmpty()) {//此处不需要判断list是否为null,因为在封装数据的时候,肯定已经有一个list了
return null;
}
if (accounts.size() > 1) {
throw new RuntimeException("结果集不唯一,请检查数据");
}
return accounts.get(0);
}
@Override
public void updateAccount(Account account) {
jdbcTemplate.update("update account set money = ? where id = ?",account.getMoney(),account.getId());
}
}
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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->
<!--配置dao-->
<bean id="accountDao" class="com.renjing.dao.impl.AccountDaoImpl">
<!--注入jdbcTemplate-->
<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 name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
</beans>
1.4.3 让dao继承JdbcDaoSupport
public class JdbcDaoSupport {
//定义对象
private JdbcTemplate jdbcTemplate;
//set方法注入数据
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
//判断数据源是否为null,为null使用数据源创建JdbcTemplate
public void setDataSource(DataSource dataSource) {
if (this.jdbcTemplate == null) {
this.jdbcTemplate = createJdbcTemplate(dataSource);
}
}
//使用数据源创建JdbcTemplate
private JdbcTemplate createJdbcTemplate(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
return jdbcTemplate;
}
}
/**
* 账户的持久层实现类
* 需要继承JdbcDaoSupport
*/
public class AccountDaoImpl2 extends JdbcDaoSupport implements IAccountDao {
@Override
public Account findAccountById(Integer id) {
List<Account> accounts = getJdbcTemplate().query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), id);
return accounts.isEmpty()?null:accounts.get(0);
}
@Override
public Account findAccountByName(String name) {
List<Account> accounts = getJdbcTemplate().query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), name);
if (accounts.isEmpty()) {//此处不需要判断list是否为null,因为在封装数据的时候,肯定已经有一个list了
return null;
}
if (accounts.size() > 1) {
throw new RuntimeException("结果集不唯一,请检查数据");
}
return accounts.get(0);
}
@Override
public void updateAccount(Account account) {
getJdbcTemplate().update("update account set money = ? where id = ?",account.getMoney(),account.getId());
}
}
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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->
<!--配置dao2-->
<bean id="accountDao2" class="com.renjing.dao.impl.AccountDaoImpl2">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置Spring内置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
</beans>
<!--配置dbcp数据源
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>-->
<!--配置c3p0数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
</bean>
dbcp的jar包:
c3p0的jar包:
注意:
- 第一种在 Dao 类中定义 JdbcTemplate 的方式,适用于所有配置方式(xml 和注解都可以)。
- 第二种让 Dao 继承 JdbcDaoSupport 的方式,只能用于基于 XML 的方式,注解用不了。