Spring的JdbcTemplate是对原始Jdbc API做的简单封装,简化了我们对于数据库的操作。
不过多的啰嗦了,直接上实例说明问题,我认为就可以了,因为这个内容并不复杂。
首先给出数据库表的支持
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;
insert into account(name,money) values('熊大',5000);
insert into account(name,money) values('熊二',5000);
insert into account(name,money) values('光头强',1000);
导入本次实例所需的jar包
<!--Spring jdbcTemplate所需的jar包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<!--Spring开发包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<!--用于数据库的连接-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<!--用于测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
编写实体类
/**
* 账户实体类
*/
public class Account {
private int id;
private String name;
private float money;
public int getId() {
return id;
}
public void setId(int 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 +
'}';
}
}
编写持久层接口及其实现类
/**
* 持久层接口
*/
public interface AccountDao {
/**
*获取所有账户信息
* @return
*/
List<Account> findAllAccount();
/**
*通过id获取账户信息
* @param id
* @return
*/
Account findAccountById(int id);
/**
* 保存账户
* @param account
*/
void saveAccount(Account account);
/**
* 更新账户
* @param account
*/
void updateAccount(Account account);
/**
* 通过id删除账户信息
* @param id
*/
void deleteAccount(int id);
}
/**
* 持久层接口实现类
*/
public class AccountDaoImpl implements AccountDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List<Account> findAllAccount() {
List<Account> accounts = jdbcTemplate.query("select *from account", new BeanPropertyRowMapper<Account>(Account.class));
return accounts;
}
public Account findAccountById(int id) {
Account account = jdbcTemplate.queryForObject("select *from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), id);
return account;
}
public void saveAccount(Account account) {
jdbcTemplate.update("insert into account(name,money)values (?,?)",account.getName(),account.getMoney());
}
public void updateAccount(Account account) {
jdbcTemplate.update("update account set name=?, money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
public void deleteAccount(int id) {
jdbcTemplate.update("delete from account where id = ?",id);
}
}
编写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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置持久层实现类-->
<bean id="accountDao" class="com.liang.dao.impl.AccountDaoImpl">
<!--注入数据库操作模版-->
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<!--配置数据库操作模版-->
<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.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/mySpring?serverTimezone=UTC"></property>
<property name="username" value="root"></property>
<property name="password" value="liang"></property>
</bean>
</beans>
编写测试类
public class JDbcTemplate {
private AccountDao accountDao;
@Before
public void init()
{
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
accountDao = (AccountDao)applicationContext.getBean("accountDao");
}
@Test
public void testFindAllAccount()
{
List<Account> accounts = accountDao.findAllAccount();
for (Account account:accounts)
{
System.out.println(account);
}
}
@Test
public void testFindAccountById()
{
Account account = accountDao.findAccountById(1);
System.out.println(account);
}
@Test
public void testSaveAccount()
{
Account account = new Account();
account.setName("小花猫");
account.setMoney(100f);
accountDao.saveAccount(account);
}
@Test
public void testUpdateAccount()
{
Account account = accountDao.findAccountById(4);
account.setMoney(10.0f);
accountDao.updateAccount(account);
}
@Test
public void testDeleteAccount()
{
accountDao.deleteAccount(4);
}
}
按照以上的方法,如果有多个持久层接口实现类的时候,便会发现有段代码的重复性很高。
其中Spring框架为我们提供了解决办法:Spring中有一个JdbcDaoSupport类,该类中定义了一个JdbcTemplate对象,可以帮助我们解决上面的重复性问题,该类在创建JdbcTemplate对象时候,需要提供一个数据源。
修改持久层实现类
/**
* 持久层接口实现类
*/
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
public List<Account> findAllAccount() {
List<Account> accounts = super.getJdbcTemplate().query("select *from account", new BeanPropertyRowMapper<Account>(Account.class));
return accounts;
}
public Account findAccountById(int id) {
Account account = super.getJdbcTemplate().queryForObject("select *from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), id);
return account;
}
public void saveAccount(Account account) {
super.getJdbcTemplate().update("insert into account(name,money)values (?,?)",account.getName(),account.getMoney());
}
public void updateAccount(Account account) {
super.getJdbcTemplate().update("update account set name=?, money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
public void deleteAccount(int id) {
super.getJdbcTemplate().update("delete from account where id = ?",id);
}
}
修改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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置持久层实现类-->
<bean id="accountDao" class="com.liang.dao.impl.AccountDaoImpl">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/itcast?serverTimezone=UTC"></property>
<property name="username" value="root"></property>
<property name="password" value="liang"></property>
</bean>
</beans>