概述
spring框架中提供的一个对象,是对原始繁琐的JdbcAPI
对象的简单封装;
开发步骤
- 1)导入spring-jdbc和spring-tx坐标;
- 2)创建数据库表和实体;
- 3)创建JdbcTemplate对象;
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
- 4)执行数据库操作。
//更新
jdbcTemplate.update(sql,params);
//查询
jdbcTemplate.query(sql,Mapper,params);
jdbcTemplate.queryForObject(sql,Mapper,params);
Spring产生JdbcTemplate对象
可以将JdbcTemplate的创建权交给Spring,将数据源DataSource的创建权也交给Spring,在Spring容器内部将数据源DataSource注入到JdbcTemplate模板对象中。
<!--加载jdbc.properties-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--数据源对象-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--jdbc模板对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
JdbcTemplate的常用操作
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateCURDTest {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void testInsert(){
int row = jdbcTemplate.update("insert into account values(?,?)","Jack",5000);
System.out.println(row);
}
@Test
public void testUpdate(){
jdbcTemplate.update("update account set money=? where name=?",8000,"Jack");
}
@Test
public void testDelete(){
jdbcTemplate.update("delete from account where name=?","Jack");
}
@Test
public void testQueryAll(){
List<Account> list = jdbcTemplate.query("select * from account",new BeanPropertyRowMapper<Account>(Account.class));
System.out.println(list);
}
@Test
public void testQueryOne(){
Account account = jdbcTemplate.queryForObject("select * from account where name=?",new BeanPropertyRowMapper<Account>(Account.class),"tom");
System.out.println(account);
}
@Test
public void testQueryCount(){
Long count = jdbcTemplate.queryForObject("select count(*) from account", Long.class);
System.out.println(count);
}