Spring框架的JdbcTemplate使用
JdbcTemplate 概述
在之前的Javaweb學(xué)習(xí)中,學(xué)習(xí)了手動(dòng)封裝JdbcTemplate,其好處是通過(sql語句+參數(shù))模板化了編程。而真正的JdbcTemplate類,是Spring框架為我們寫好的。它是 Spring 框架中提供的一個(gè)對(duì)象,是對(duì)原始 Jdbc API 對(duì)象的簡(jiǎn)單封裝。除了JdbcTemplate,spring 框架還為我們提供了很多的操作模板類。
- 操作關(guān)系型數(shù)據(jù)的:
JdbcTemplate和HibernateTemplate。 - 操作 nosql 數(shù)據(jù)庫的:RedisTemplate。
- 操作消息隊(duì)列的:JmsTemplate。
Spring框架的JdbcTemplate在spring-jdbc的jar包中,,除了要導(dǎo)入這個(gè) jar 包
外,還需要導(dǎo)入一個(gè) spring-tx的jar包(它是和事務(wù)相關(guān)的)。當(dāng)然連接池的jar包也不能忘記,這里使用的是c3p0。
使用JdbcTemplate一定要導(dǎo)入Spring的數(shù)據(jù)庫模塊的三個(gè)jar:

使用JdbcTemplate可以快捷的操作數(shù)據(jù)庫,本文章針對(duì)JdbcTemplate進(jìn)行演示。本文所使用的數(shù)據(jù)庫表為jdbctemplate中的employee,表的內(nèi)容如下。

對(duì)JdbcTemplate進(jìn)行分步演示
1:測(cè)試數(shù)據(jù)源
數(shù)據(jù)庫配置文件
jdbctemplate數(shù)據(jù)庫在本地?cái)?shù)據(jù)庫中已經(jīng)創(chuàng)建。
jdbc.user=root jdbc.password=Hudie jdbc.jdbcUrl=jdbc:mysql://localhost:3306/jdbctemplate jdbc.driverClass=com.mysql.jdbc.Driver
xml配置文件
<!-- 引入外部配置文件 -->
<context:property-placeholder location="classpath:dbconfig.properties" />
<!-- 配置數(shù)據(jù)源 -->
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
</bean>
測(cè)試獲取連接
public class txTest {
ApplicationContext ioc = new ClassPathXmlApplicationContext("ApplicationContext.xml");
@Test
public void test() throws SQLException {
DataSource bean = ioc.getBean(DataSource.class);
Connection connection = bean.getConnection();
System.out.println(connection);
connection.close();
}
}
執(zhí)行測(cè)試,成功獲取到連接。

2:為IoC容器配置一個(gè)JdbcTemplate
如果通過編碼來進(jìn)行獲得一個(gè)JdbcTemplate對(duì)象,可以使用new JdbcTemplate(dataSource);,不過由于這個(gè)對(duì)象經(jīng)常使用,將其放在IoC容器中更合適。
具體配置如下:
<!-- Spring提供了一個(gè)JdbcTmplate來操作數(shù)據(jù)庫 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <constructor-arg name="dataSource" ref="dataSource"></constructor-arg> </bean>
測(cè)試
public class txTest {
ApplicationContext ioc = new ClassPathXmlApplicationContext("ApplicationContext.xml");
JdbcTemplate jdbcTemplate= ioc.getBean(JdbcTemplate.class);
@Test
public void test2() {
System.out.println(jdbcTemplate);
}
}
成功打印出JdbcTemplate對(duì)象。

3:更新
將emp_id=5的記錄salary字段改為1300.00
jdbcTemplate.updat():表示更新一條記錄。
@Test
public void test3() {
String sql = "update employee set salary = ? where emp_id=?;";
int update = jdbcTemplate.update(sql, 1300.00, 5);
System.out.println("更新員工表,影響" + update + "行");
}

4:批量插入
jdbcTemplate.batchUpdate(sql, batchArgs):表示批量進(jìn)行插入,插入一個(gè)list集合,返回的是影響的行數(shù)。
@Test
public void test4() {
String sql = "insert into employee (emp_name,salary) values(?,?)";
List<Object[]> batchArgs = new ArrayList<Object[]>();
batchArgs.add(new Object[] { "張三", 998.98 });
batchArgs.add(new Object[] { "李四", 998.98 });
batchArgs.add(new Object[] { "王五", 998.98 });
batchArgs.add(new Object[] { "趙六", 998.98 });
// List的長度就是sql語句執(zhí)行的次數(shù)
int[] is = jdbcTemplate.batchUpdate(sql, batchArgs);
for (int i : is) {
System.out.println(i);
}
}
int[] is = jdbcTemplate.batchUpdate(sql, batchArgs);返回的結(jié)果是影響的行數(shù)。

5:查詢emp_id=5的記錄,封裝為一個(gè)Java對(duì)象返回。
創(chuàng)建JavaBean
package com.gql.bean;
public class Employee {
private Integer empId;
private String empName;
private Double salary;
//省略setter、getter與toString方法。
}
查詢并封裝單條記錄
@Test
public void test5() {
String sql = "select emp_id empId,emp_name empName,salary from employee where emp_id=?";
// rowMapper:規(guī)定每一行記錄和JavaBean的屬性如何映射
Employee employee = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Employee.class), 5);
System.out.println(employee);
}

6:查詢salary>4000的記錄,封裝為List集合返回
@Test
public void test6() {
String sql = "select emp_id empId,emp_name empName,salary from employee where salary>?";
List<Employee> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Employee.class), 4000);
for (Employee employee : list) {
System.out.println(employee);
}
}
成功將salary>400的記錄封裝進(jìn)list集合。

7:查詢最大的salary
使用mysql的max函數(shù)可以獲得最大的salary,調(diào)用queryForObject方法,返回Double類型。
@Test
public void test7() {
String sql = "select max(salary) from employee";
Double object = jdbcTemplate.queryForObject(sql, Double.class);
System.out.println("最高工資是:" + object);
}

8:使用具名參數(shù)SQL插入一條員工記錄,并以Map形式傳入?yún)?shù)值。
Spring中使用namedParameterJdbcTemplate來進(jìn)行含有具名SQL的操作。
將namedParameterJdbcTemplate加到IoC容器中。
<!-- 配置一個(gè)具名參數(shù)的Jdbctemplate --> <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> <!-- 使用構(gòu)造器注入一個(gè)數(shù)據(jù)源 --> <constructor-arg name="dataSource" ref="dataSource"></constructor-arg> </bean>
在測(cè)試中以Map形式傳入?yún)?shù)值。
public class txTest {
ApplicationContext ioc = new ClassPathXmlApplicationContext("ApplicationContext.xml");
JdbcTemplate jdbcTemplate = ioc.getBean(JdbcTemplate.class);
NamedParameterJdbcTemplate namedJdbcTemplate = ioc.getBean(NamedParameterJdbcTemplate.class);
@Test
public void test9() {
String sql = "insert into employee (emp_name,salary) values(:empName,:salary)";
Map<String, Object> paramMap = new HashMap<>();
// 將所有具名參數(shù)的值都放在map中
paramMap.put("empName", "小紅");
paramMap.put("salary", 12000.00);
int update = namedJdbcTemplate.update(sql, paramMap);
System.out.println(update);
}
}
9:使用具名參數(shù)SQL插入一條員工記錄,并以SqlparamSource傳入?yún)?shù)值。
與上一條實(shí)驗(yàn)類似,只是選用了不同的參數(shù)類型。
@Test
public void test10() {
String sql = "insert into employee (emp_name,salary) values(:empName,:salary)";
Employee employee = new Employee();
employee.setEmpName("小藍(lán)");
employee.setSalary(9999.00);
int i = namedJdbcTemplate.update(sql, new BeanPropertySqlParameterSource(employee));
System.out.println(i);
}
到此這篇關(guān)于Spring框架的JdbcTemplate使用的文章就介紹到這了,更多相關(guān)Spring JdbcTemplate內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java遞歸實(shí)現(xiàn)復(fù)制一個(gè)文件夾下所有文件功能
這篇文章主要介紹了java遞歸實(shí)現(xiàn)復(fù)制一個(gè)文件夾下所有文件功能n次,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-08-08
SpringBoot實(shí)現(xiàn)統(tǒng)一功能處理的教程詳解
這篇文章主要為大家詳細(xì)介紹了SpringBoot如何實(shí)現(xiàn)統(tǒng)一功能處理,文中的示例代碼講解詳細(xì),對(duì)大家學(xué)習(xí)或工作有一定借鑒價(jià)值,感興趣的同學(xué)可以參考閱讀下2023-05-05
淺析Java中對(duì)稱與非對(duì)稱加密算法原理與使用
密碼學(xué)是研究編制密碼和破譯密碼的技術(shù)科學(xué)。這篇文章主要為大家介紹了Java中對(duì)稱與非對(duì)稱加密算法的原理與使用,感興趣的小伙伴可以了解一下2023-03-03
java使用ArrayList遍歷及效率比較實(shí)例分析
這篇文章主要介紹了java使用ArrayList遍歷及效率比較,實(shí)例分析了ArrayList遍歷的方法與使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07
Servlet+JDBC實(shí)現(xiàn)登陸功能的小例子(帶驗(yàn)證碼)
這篇文章主要介紹了Servlet+JDBC實(shí)現(xiàn)登陸功能的小例子(帶驗(yàn)證碼),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
SpringBoot中動(dòng)態(tài)數(shù)據(jù)源是實(shí)現(xiàn)與用途
這篇文章主要是來和大家討論一下SpringBoot中動(dòng)態(tài)數(shù)據(jù)源是實(shí)現(xiàn)與用途,文中的示例代碼簡(jiǎn)潔易懂,具有一定的學(xué)習(xí)價(jià)值,感興趣的可以了解一下2023-08-08

