Spring_JDBCTemplate和事务控制
JDBCTemplate
它是Spring提供的一个对象,是对原始的Jdbc Api对象的简单封装。Spring提供了很多操作模版类。
- 操作关系型数据库:JdbcTemplate、HibernateTemplate
- 操作nosql数据库:RedisTemplate
- 操作消息队列:JmsTemplate
JdbcTemplate作用
用于和数据库交互,实现对表的CRUD操作。
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
https://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/spring?useSSL=false"></property>
<property name="username" value="root"></property>
<property name="password" value="welcome1"></property>
</bean>
</beans>
//获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
//获取JdbcTemplate对象
JdbcTemplate jt = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
JdbcTemplate的CRUD
public static void main(String[] args) {
//获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
//获取JdbcTemplate对象
JdbcTemplate jt = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
//执行操作
//保存
jt.update("insert into account(name,money) values (?,?)", "fff", 1000f);
//更新
jt.update("update account set name=?,money=? where id=?","update_test",4567f,7);
//删除
jt.update("delete from account where id=?",6);
//查询所有
//new BeanPropertyRowMapper<Account>(Account.class)想当于DBUtils中当BeanHandler。
List<Account> accounts = jt.query("select * from account where id>?", new BeanPropertyRowMapper<Account>(Account.class), 3);
for (Account account : accounts) {
System.out.println(account);
}
//查询一个
List<Account> accounts1 = jt.query("select * from account where id=?", new BeanPropertyRowMapper<Account>(Account.class), 3);
System.out.println(accounts1.isEmpty() ? "没有内容" : accounts1.get(0));
//聚合函数
Long count = jt.queryForObject("select count(*) from account where id > ?",Long.class,2);
System.out.println(count);
}
JdbcTemplate在DAO中的操作
/*** 持久层接口*/
public interface AccountDao {
Account findAccountById(Integer id);//根据id查询账户
Account findAccountByName(String name);//根据名称查询账户
void updateAccount(Account account);//更新账户
}
/********************************************************************************************************************************************************************************************/
public class