数据库操作模板JdbcTemplate和事务控制
数据库操作模板JdbcTemplate
JdbcTemplate概述
JdbcTemplate是Spring框架中提供的一个对象,对原始的JDBC API进行简单封装,其用法与DBUtils类似.
JdbcTemplate对象的创建
使用Spring内置的数据源DriverManagerDataSource,需要在bean.xml中配置如下:
<!--配置jdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置DataSource-->
<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/day17"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
JdbcTemplate的增删改查操作
实现增删改
JdbcTemplateDemo类:
public static void main(String[] args) {
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
JdbcTemplate jt =ac.getBean("jdbcTemplate",JdbcTemplate.class);
//3.执行操作
//保存操作
//jt.update("insert into account(name,money)values(?,?)","名字",5000);
//更新操作
//jt.update("update account set money = money-? where id = ?",300,6);
//删除操作
//jt.update("delete from account where id = ?",6);
}}
查询
//1.查询所有
List<Account> accounts = jt.query("select * from account where money > ?",
new BeanPropertyRowMapper<Account>(Account.class),1000f);
for (Account account : accounts) {
System.out.println(account);
}
//2.查询一个
List<Account> accounts = jt.query("select * from account where id = ?",
new BeanPropertyRowMapper<Account>(Account.class),1);
System.out.println(accounts.isEmpty()?"无内容":accounts.get(0));
//3.聚合查询
Long count = jt.queryForObject("select count(*) from account where money > ?",Long.class,1000f);
System.out.println(count);
在DAO使用JdbcTemplate
1.第一种方式
在DAO中定义jdbctemplate
注入jdbctemplate
<!--配置账户的持久层-->
<bean id="accountDao" class="com.itheima.dao.impl.IAccountDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<!--配置jdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
实现类
//账户的持久层实现类
public class AccountDaoImpl implements IAccountDao {
private JdbcTemplate jdbcTemplate; // JdbcTemplate对象