文章目录
JdbcTemplate是对JDBC API的进一步封装,简化了java操作数据库的步骤。
注意:本章是在Spring-配置数据源的基础上进行操作的。
1 引入依赖
spring-jdbc包:
<!--JdbcTemplate-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.13</version>
</dependency>
spring-jdbc依赖spring-tx包:
2 创建JdbcTemplate对象
三种等价的创建JdbcTemplate对象的方法。
2.1 new
public JdbcTemplate getJdbcTemplate(DataSource dataSource){
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);//设置数据源
return jdbcTemplate;
}
2.2 xml文件
applicationContext.xml配置,将创建JdbcTemplate对象的工作交给spring容器。
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
2.3 注解方式
使用@Bean,将创建JdbcTemplate对象的工作交给spring容器。
public class JdbcConfig {
@Autowired
private DataSource dataSource;
@Bean("jdbcTemplate")
public JdbcTemplate getJdbcTemplate(){
return new JdbcTemplate(dataSource);
}
}
JdbcConfig导入主配置类中:
@ComponentScan("com.test")
@Import({
DataSourceConfig.class,JdbcConfig.class})
@EnableAspectJAutoProxy
public class ApplicationConfig {
}
3 操作数据库
创建tb_account表:
create table tb_account (
id int auto_increment primary key,
account_name varchar(50) not null,
account_id varchar(50) not null,
money decimal(19,4)
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ;
实体类:
public class Account {
private int i