一、Spring的JDBC的模板
Spring是EE开发的一站式的框架,有EE开发的每层的解决方案。Spring对持久层也提供了解决方案:ORM模块和JDBC的模板。
Spring提供了很多的模板用于简化开发:
二、JDBC模板使用入门
1. 首先自然先创建web项目,并导入所需jar包和log4j.properties文件,具体如下:
分别是两个日志相关的包、MySQL数据库驱动包、Spring核心开发包、jdbc相关包以及 事务相关包。
2. 创建数据库和数据库表:
CREATE DATABASE spring4;
USE spring4;
CREATE TABLE account(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20),
money DOUBLE
);
3. 测试代码,如向数据库插入数据,具体代码如下示:
@Test
//Jdbc模板的使用类似于DBUtils
public void demo() {
//1.创建连接池
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///spring4");
dataSource.setUsername("root");
dataSource.setPassword("abc123!");
//2.创建JDBC模板
JdbcTemplate template = new JdbcTemplate(dataSource);
//增删改方法都是使用update方法
template.update("insert into account values (null,?,?)", "川普",1522);
}
三、将连接池和模板交由Spring管理
上面我们是直接用代码的形式来创建连接池和JDBC模板,显然这种代码编写会造成代码复用性和耦合性变差,下面我们将连接池和JDBC模板交给Spring管理。
1. 引入所需jar包
2. 引入配置文件并配置连接池和Jdbc模板
<?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:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 配置Spring的内置连接池 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 属性注入 -->
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///spring4"/>
<property name="username" value="root"/>
<property name="password" value="abc123!"/>
</bean>
<!-- 配置Spring的JDBC模板 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 注入Spring的内置连接池,因为需要根据连接池创建模板 -->
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
注意:连接池中的property标签中的name的值"driverClassName",“url”,“username”,"password"以及jdbc模板中的name的值"dataSource"这些字段都是默认规定好的,切不可更改,注意大小写。
3. 测试代码,如向数据库插入数据,具体代码如下示:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcDemo {
@Resource(name="jdbcTemplate")//注入模板
private JdbcTemplate jdbcTemplate;
@Test
public void demo() {
jdbcTemplate.update("insert into account values (null,?,?)", "川普",1522);
}
}
四、使用第三方数据库连接池
DBCP的使用
1. 导入所需jar包
2. 配置DBCP连接池
<!-- 配置dbcp连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<!-- 属性注入 -->
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///spring4"/>
<property name="username" value="root"/>
<property name="password" value="abc123!"/>
</bean>
C3P0的使用
1. 引入c3p0连接池jar包
2. 配置C3P0连接池
<!-- 配置C3P0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 属性注入 -->
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql:///spring4"/>
<property name="user" value="root"/>
<property name="password" value="abc123!"/>
</bean>
注意一下连接池中的property标签中的name的写法。
五、抽取数据库配置到属性文件
1. 创建一个数据库属性文件jdbc.proerties,具体内容如下所示:
## MySQL数据库属性配置
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring4
jdbc.username=root
jdbc.password=abc123!
2. 引入属性文件
- 第一种方式引入:
<!-- 第一种方式通过一个bean标签引入(很少) --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"/> </bean>
- 第二种方式引入:
<!-- 第二种方式通过context标签引入 --> <context:property-placeholder location="classpath:jdbc.properties"/>
3. 引入属性文件中的属性值,以C3P0连接池为例
<!-- 配置C3P0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 属性注入 -->
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
六、JDBC模板的CRUD
保存操作
@Test
//添加操作
public void testInsert() {
jdbcTemplate.update("insert into account values (null,?,?)", "川普",1522);
}
更新操作
@Test
//更新操作
public void testUpdate() {
jdbcTemplate.update("update account set name = ? where id = ?","希拉里",10);
}
删除操作
@Test
//删除操作
public void testDelete() {
jdbcTemplate.update("delete from account where id = ?", 12);
}
查询操作
查询某个属性
@Test
//查询获取表的某个字段
public void testSelect() {
//String.class表示返回值类型,10为id值
String name = jdbcTemplate.queryForObject("select name from account where id = ?", String.class, 10);
System.out.println(name);
}
统计查询
@Test
//统计查询
public void testSelectCount() {
Long count = jdbcTemplate.queryForObject("select count(*) from account", Long.class);
System.out.println(count);
}
查询返回对象
首先需要定义如下一个POJO,用于封装数据库查询的数据到对象中,具体代码如下:
public class Account {
private Integer id;
private String name;
private Double money;
public Account() {
super();
}
public Account(Integer id, String name, Double money) {
super();
this.id = id;
this.name = name;
this.money = money;
}
//setter,getter,toString
}
然后在定义一个类MyRowMapper,该类用于封装数据,具体代码如下:
/**
* 该类用于将数据库中查询的数据封装到POJO中
* @author 郑松涛
*
*/
public class MyRowMapper implements RowMapper<Account>{
/**
* 需要手动完成数据到Account对象的封装
*/
@Override
public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
Account account = new Account();
account.setId(rs.getInt("id"));
account.setName(rs.getString("name"));
account.setMoney(rs.getDouble("money"));
return account;
}
}
然后现在可以使用jdbcTemplate去执行查询操作了,代码如下:
@Test
//查询并封装到一个对象中
public void testSelectObject() {
Account account = jdbcTemplate.queryForObject("select * from account where id = ?", new MyRowMapper(), 5);
System.out.println(account);//Account [id=5, name=钱七, money=6545.0]
}
查询返回集合
@Test
//查询多条数据
public void testSelectList() {
List<Account> accountList = jdbcTemplate.query("select * from account", new MyRowMapper());
for (Account account : accountList) {
System.out.println(account);
}
}