Spring JdbcTemplate基本使用
1.1 JdbcTemplate概述
它是spring框架中提供的一个对象,是对原始繁琐的Jdbc API对象的简单封装。spring框架为我们提供了很多的操作模板类。例如:操作关系型数据的JdbcTemplate和HibernateTemplate,操作nosql数据库的RedisTemplate,操作消息队列的JmsTemplate等等。
1.2JdbcTemplate开发步骤
1.2.1大致步骤
- 导入spring-jdbc和spring-tx坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.14.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.15.RELEASE</version>
</dependency>
-
创建数据库表和实体
-
创建JdbcTemplate对象
//测试jdbc开发步骤
public void test1() throws PropertyVetoException {
//创建数据源对象,添加jdbc.properties中内容
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUser("root");
dataSource.setPassword("root");
//产生jdbc模板对象,让这个对象来操作数据库
JdbcTemplate jdbcTemplate = new JdbcTemplate();
//设置数据源对象,知道数据库在哪
jdbcTemplate.setDataSource(dataSource);
int tom = jdbcTemplate.update("insert into account values(?,?)", "tom", 5000);
System.out.println(tom);
}
- 执行数据库操作
1.2.2spring创建JdbcTemplate
上述过程,太繁琐,不如交给spring来做,创建数据库对象和设置数据源对象
- 创建applicationContext.xml
<!--配置数据源对象-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
//这里的数据源没有写死,直接导入外部的数据库,需要修改时在外部修改,这里面就不动了直接加载外部jdbc.properties就行
<!-- 加载外部jdbc.properties-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置jdbc模板对象-->
<bean id="jdbcTemplete" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
测试类中进行测试
@Test
//测试spring产生jdbcTemplete对象
public void test2() throws PropertyVetoException {
//老朋友了,spring帮我们创建对象
ClassPathXmlApplicationContext app =
new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jdbcTemplate = app.getBean(JdbcTemplate.class);
int zs = jdbcTemplate.update("insert into account values(?,?)", "zhangsan ", 5000);
System.out.println(zs);
}