1.JdbcTemplate是什么
它是spring框架中提供的一个对象,是对原始繁琐的Jdbc API对象的简单封装。spring框架为我们提供了很多的操作模板类。例如:操作关系型数据的JdbcTemplate和HibernateTemplate,操作nosql数据库的RedisTemplate,操 作消息队列的JmsTemplate等等。
2. JdbcTemplate操作
① 导入spring-jdbc和spring-tx坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
② 创建数据库表和实体
CREATE DATABASE test1
USE test1
CREATE TABLE `account`(
`name` VARCHAR(50),
`money` INT)
SELECT * FROM ACCOUNT
③ 创建JdbcTemplate对象和配置文件
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
此处使用的是jdbc配置文件注入
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driver}"></property>
<property name="jdbcUrl" value="${url}"></property>
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="datasource"></property>
</bean>
④ 执行数据库操作CRUD
此处使用3种API,3种情况 1.进行增删改操作是jdbcTemplate.update()操作 2.进行查询 查询所有数据
@Test
public void testQueryAll(){
List<Account> accounts = jdbcTemplate.query("select * from account", new
BeanPropertyRowMapper<Account>(Account.class));
for (Account account : accounts) {
System.out.println(account.getName());
}
}
查询单个数据
//测试查询单个对象操作
public void testQueryOne(){
Account account = jdbcTemplate.queryForObject("select * from account where
name=?", new BeanPropertyRowMapper<Account>(Account.class), "tom");
System.out.println(account.getName());
}
聚合查询
public void testQueryCount(){
Long aLong = jdbcTemplate.queryForObject("select count(*) from account",
Long.class);
System.out.println(aLong);
}