什么是模板技术
Spring框架中国提供了很多支持持久层的模板类来简化编程,使用模板写程序会变得简单
spring框架提供xxxTemplate
jdbcTemplate类
spring框架提供了jdbc模板
概念
jdbcTemplate类、connection---连接、statement resultset-----管理事务
JDBC模板类的使用
需要导入两个依赖(处理数据的、事务的)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
编写测试类(所有的sql语句分为两种select、update)
@Test
public void run1(){
// 创建连接池对象,Spring框架内置了连接池对象
DriverManagerDataSource dataSource = new DriverManagerDataSource();
// 设置4个参数
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///spring_db");
dataSource.setUsername("root");
dataSource.setPassword("root");
// 提供模板,创建对象
JdbcTemplate template = new JdbcTemplate(dataSource);
// 完成数据的增删改查
template.update("insert into account values (null,?,?)","熊大",1000);
}
使用spring框架来管理模板类
在配置文件application.xml文件中
<!--配置连接池-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql:///spring_db" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!--配置jdbc模板-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:applicationContext_jdbc.xml")
public class Demo1_1 {
@Autowired
private JdbcTemplate jdbcTemplate;
/**
* 测试的方式
*/
@Test
public void run1(){
jdbcTemplate.update("insert into account values (null,?,?)","熊二",500);
}
}