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

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

對JdbcTemplate進行分步演示
1:測試數(shù)據(jù)源
數(shù)據(jù)庫配置文件
jdbctemplate數(shù)據(jù)庫在本地數(shù)據(jù)庫中已經創(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>
測試獲取連接
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í)行測試,成功獲取到連接。

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

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):表示批量進行插入,插入一個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);返回的結果是影響的行數(shù)。

5:查詢emp_id=5的記錄,封裝為一個Java對象返回。
創(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的記錄封裝進list集合。

7:查詢最大的salary
使用mysql的max函數(shù)可以獲得最大的salary,調用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形式傳入參數(shù)值。
Spring中使用namedParameterJdbcTemplate來進行含有具名SQL的操作。
將namedParameterJdbcTemplate加到IoC容器中。
<!-- 配置一個具名參數(shù)的Jdbctemplate --> <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> <!-- 使用構造器注入一個數(shù)據(jù)源 --> <constructor-arg name="dataSource" ref="dataSource"></constructor-arg> </bean>
在測試中以Map形式傳入參數(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傳入參數(shù)值。
與上一條實驗類似,只是選用了不同的參數(shù)類型。
@Test
public void test10() {
String sql = "insert into employee (emp_name,salary) values(:empName,:salary)";
Employee employee = new Employee();
employee.setEmpName("小藍");
employee.setSalary(9999.00);
int i = namedJdbcTemplate.update(sql, new BeanPropertySqlParameterSource(employee));
System.out.println(i);
}
到此這篇關于Spring框架的JdbcTemplate使用的文章就介紹到這了,更多相關Spring JdbcTemplate內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java連接MYSQL數(shù)據(jù)庫的實現(xiàn)步驟
以下的文章主要描述的是java連接MYSQL數(shù)據(jù)庫的正確操作步驟,在此篇文章里我們主要是以實例列舉的方式來引出其具體介紹2013-06-06
Spring Boot集成Shiro并利用MongoDB做Session存儲的方法詳解
這篇文章主要給大家介紹了關于Spring Boot集成Shiro并利用MongoDB做Session存儲的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友下面來一起看看吧。2017-12-12
Jmeter連接Mysql數(shù)據(jù)庫實現(xiàn)過程詳解
這篇文章主要介紹了Jmeter連接Mysql數(shù)據(jù)庫實現(xiàn)過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-08-08
mybatis中方法返回泛型與resultType不一致的解決
這篇文章主要介紹了mybatis中方法返回泛型與resultType不一致的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07

