JdbcTemplate是spring对JDBC的封装,目的是使JDBC更易于使用,JdbcTemplate是Spring的一部分,JdbcTemplate处理了资源的建立和释放,帮我们避免一些常见的错误,比如忘记关闭连接。它运行核心的JDBC工作流,如Statement的建立和执行,而我们只需要提供SQL语句和提取结果。
提供的操作模板类:
- 操作关系型数据库
- JdbcTemplate
- HibernateTemplate
- 操作nosql数据库
- RedisTemplate
- 操作消息队列
- JmsTemplate
JdbcTemplate的基本使用
首先添加坐标:
<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>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
实体类:
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
//省略get、set、toString方法
}
测试:
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/db4");
ds.setUsername("root");
ds.setPassword("123456");
JdbcTemplate jt = new JdbcTemplate();
jt.setDataSource(ds);
jt.execute("insert into account(name,money)values('张三',1000)");//执行
//保存
//jt.update("insert into account(name,money)values(?,?)", "李四", 100);
//更新
//jt.update("update account set money=money-? where id=?",3,100);
//删除
//jt.update("delete from account where id=?",3);
//查询所有
//List<Account> accounts = jt.query("select * from account where money>?", new AccountRowMapper(), 500f);
//查询所有简化版,不用写RowMapper的实现类
//List<Account> accounts = jt.query("select * from account where money>?", new BeanPropertyRowMapper<Account>(Account.class),500f);
//for (Account account : accounts) {
// System.out.println(account);
//}
//查询一个
List<Account> accounts = jt.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),1);
System.out.println(accounts.isEmpty()?"没有内容":accounts.get(0));
//查询返回一行一列(使用聚合函数,但不加group by子句)
Long count = jt.queryForObject("select count(*) from account where money > ?",Long.class,1000f);
System.out.println(count);
//如何自己实现RowMapper接口
class AccountRowMapper implements RowMapper<Account>{
//把结果集中的数据封装到Account中,然后由spring把每个Account加到集合中
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;
}
}
在Dao中使用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">
<!-- 配置账户的持久层-->
<bean id="accountDao" class="com.mantishell.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/db4"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
</beans>
添加dao的接口,以及实现类
public interface IAccountDao {
Account findAccountById(Integer accountId);
Account findAccountByName(String accountName);
void updateAccount(Account account);
}
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 name = ?",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());
}
}
测试:
public static void main(String[] args) {
//1、获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2、获取对象
IAccountDao accountDao = ac.getBean("accountDao", IAccountDao.class);
Account account = accountDao.findAccountById(1);
System.out.println(account);
account.setMoney(100f);
accountDao.updateAccount(account);
}