JdbcTemplate
- 🦒看一個實際需求
- 🦒官方文檔
- 🦒基本介紹
- 🦒使用實例
- 📕需求說明
- 📕代碼演示
🦒看一個實際需求
實際需求: 如果程序員就希望使用spring框架來做項目, spring框架如何處理對數據庫的操作呢?
- 方案1: 使用前面做項目開發的
JdbcUtils
類 - 方案2: 其實spring提供了一個操作數據庫(表)功能強大的類
JdbcTemplate
. 我們可以同ioc
容器來配置一個jdbcTemplate
對象, 使用它來完成對數據庫表的各種操作.
🦒官方文檔
官方文檔: spring-framework-5.3.8\docs\javadoc-api\index.html
🦒基本介紹
1.通過Spring
可以配置數據源, 從而完成對數據表的操作
2.JdbcTemplate
是Spring
提供的訪問數據庫的技術. 可以將JDBC
的常用操作封裝為模板方法. [JdbcTemplate
類圖]
🦒使用實例
📕需求說明
我們使用spring
的方式來完成 JdbcTemplate
配置和使用
📕代碼演示
找到前面我們搭建的spring項目, 在此項目上學習 JdbcTemplate
.
1.引入使用JdbcTemplate需要的jar包
2.創建數據庫 spring
和表 monster
1)管理員打開cmd窗口, 開啟數據庫服務. 別忘了, 這很重要
安裝Mysql5.7
2)sql
代碼
-- 創建數據庫
CREATE DATABASE spring;
USE spring;
-- 創建表
CREATE TABLE monster (id INT UNSIGNED PRIMARY KEY,`name` VARCHAR(64) NOT NULL DEFAULT '',skill VARCHAR(64) NOT NULL DEFAULT ''
)CHARSET=utf8;
INSERT INTO monster VALUES(100, '孫悟空', '金箍棒');
INSERT INTO monster VALUES(200, '紅孩兒', '三昧真火');
INSERT INTO monster VALUES(300, '鐵扇公主', '芭蕉扇');
3.創建配置文件 src/jdbc.properties
JdbcTemplate
會使用到DataSource
, 而DataSource
可以拿到連接去操作數據庫
jdbc.user=root
jdbc.pwd=zzw
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
4.創建配置文件 src/JdbcTemplate_ioc.xml
通過屬性文件配置bean, 參考
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><!--引入外部的jdbc.properties文件--><context:property-placeholder location="classpath:jdbc.properties"/><!--配置數據源對象-DataSource--><bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource"><!--給數據源對象配置屬性值--><property name="user" value="${jdbc.user}"/><property name="password" value="${jdbc.pwd}"/><property name="driverClass" value="${jdbc.driver}"/><property name="jdbcUrl" value="${jdbc.url}"/></bean>
</beans>
5.新建測試類com.zzw.spring.test.JdbcTemplateTest
public class JdbcTemplateTest {@Testpublic void testDataSourceByJdbcTemplate() {//獲取容器ApplicationContext ioc =new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");//在這里打個斷點System.out.println("ok");}
}
public class JdbcTemplateTest {@Testpublic void testDataSourceByJdbcTemplate() {//獲取容器ApplicationContext ioc =new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");//因為ComboPooledDataSource類實現了DataSource接口, 所以我們可以用接口類型來獲取 comboPooledDataSource對象DataSource dataSource = ioc.getBean(DataSource.class);Connection connection = dataSource.getConnection();//獲取到connection=com.mchange.v2.c3p0.impl.NewProxyConnection@2cd2a21fSystem.out.println("獲取到connection=" + connection);connection.close();System.out.println("ok");}
}
6.配置JdbcTemplate_ioc.xml
, 將數據源分配給JdbcTemplate bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><!--引入外部的jdbc.properties文件--><context:property-placeholder location="classpath:jdbc.properties"/><!--配置數據源對象-DataSource--><bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource"><!--給數據源對象配置屬性值--><property name="user" value="${jdbc.user}"/><property name="password" value="${jdbc.pwd}"/><property name="driverClass" value="${jdbc.driver}"/><property name="jdbcUrl" value="${jdbc.url}"/></bean><!--配置JdbcTemplate對象--><!--JdbcTemplate會使用到DataSource, 而DataSource可以拿到連接去操作數據庫--><bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate"><!--給JdbcTemplate對象配置dateSource--><property name="dataSource" ref="dataSource"/></bean>
</beans>
7.修改JdbcTemplateTest.java
, 通過JdbcTemplate
對象完成添加一個新的 monster
public class JdbcTemplateTest {@Testpublic void addDataByJdbcTemplate() {//獲取到容器ApplicationContext ioc =new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");//獲取JdbcTemplate對象, 這里我們先 debug一下System.out.println("ok");}
}
public class JdbcTemplateTest {@Testpublic void addDataByJdbcTemplate() {//獲取到容器ApplicationContext ioc =new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");//獲取JdbcTemplate對象 [按類型獲取]JdbcTemplate jdbcTemplate = ioc.getBean(JdbcTemplate.class);//1.添加方式①//String sql = "insert into monster values(400, '陸小千', '魔幻手機')";//jdbcTemplate.execute(sql);//2.添加方式② ?占位符, 可以防止sql注入String sql = "insert into monster values(?, ?, ?)";//affected表示 執行后表受影響的行數int affected = jdbcTemplate.update(sql, 500, "金角大王", "紫金紅葫蘆");System.out.println("add success afftected=" + affected);}
}
8.修改JdbcTemplateTest.java
, 通過JdbcTemplate
對象完成更新一個 monster
的 skill
public class JdbcTemplateTest {//測試通過JdbcTemplate對象完成修改數據@Testpublic void updateDataByJdbcTemplate() {//獲取到容器ApplicationContext ioc =new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");//獲取JdbcTemplate對象JdbcTemplate jdbcTemplate = ioc.getBean(JdbcTemplate.class);//組織SQLString sql = "update monster set skill = ? where id = ?";//假使修改后的數據和修改前的數據一樣, 也認為是修改成功了一條語句, affected返回 1, 因為它沒有判斷要修改的數據int affected = jdbcTemplate.update(sql, "美人計", 300);System.out.println("update ok affected=" + affected);}
}
9.修改JdbcTemplateTest.java
, 通過JdbcTemplate
對象完成批量添加兩個 monster
白蛇精和豬八戒
public class JdbcTemplateTest {//測試通過JdbcTemplate對象完成批量添加數據//這里有一個使用API的技巧/*** 說明* 1.對于某些類, 有很多API, 使用的步驟* 2.使用技巧: (1)先確定API名字 (2)根據API提供相應的參數 [組織參數]* (3)把自己的調用思路清晰 (4)根據API, 可以推測類的用法和功能*/@Testpublic void addBatchDataByJdbcTemplate() {//獲取到容器ApplicationContext ioc =new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");//獲取JdbcTemplate對象JdbcTemplate jdbcTemplate = ioc.getBean(JdbcTemplate.class);//1.先確定, 猜測API名稱 update -> batchUpdate [如果出現問題,再重新找]//public int[] batchUpdate(String sql, List<Object[]> batchArgs){}//2.準備參數 [構建實參]String sql = "insert into monster values(?, ?, ?)";List<Object[]> batchArgs = new ArrayList<>();batchArgs.add(new Object[]{600, "鼠鼠", "偷吃糧食"});batchArgs.add(new Object[]{700, "貓貓", "抓老鼠"});//3.調用//說明: 返回結果是一個數組, 每個元素對應上面的sql語句對表的影響記錄數int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);//輸出for (int anInt : ints) {System.out.println("anInt=" + anInt);}System.out.println("batch add ok~");}
}
10.查詢 id=100
的 monster
并封裝到 Monster
實體對象
1)創建Monster實體類, 跳轉
2)這里有一個知識點: 給字段起別名, 應對應實體類的屬性
. 我們在前面的家居購項目中遇到過
public class JdbcTemplateTest {/*** 查詢id=100的monster對象封裝到Monter實體對象[在實際開發中非常有用]*/@Testpublic void selectDataByJdbcTemplate() {//獲取到容器ApplicationContext ioc =new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");//獲取JdbcTemplate對象JdbcTemplate jdbcTemplate = ioc.getBean(JdbcTemplate.class);//1.確定API query -> queryForObject//public <T> T queryForObject(String sql, RowMapper<T> rowMapper, @Nullable Object... args)//2.準備參數String sql = "SELECT id AS monsterId, `name`, skill FROM monster WHERE id = ?";//使用了RowMapper 接口來對返回的數據, 進行一個封裝 底層使用的反射 -> setter方法//細節: 你查詢的記錄的表的字段需要和 Monster對象的字段名保持一致RowMapper<Monster> rowMapper = new BeanPropertyRowMapper<>();//3.調用Monster monster = jdbcTemplate.queryForObject(sql, rowMapper, 100);//輸出System.out.println("monster=" + monster);System.out.println("query ok~");}
}
3)結果報錯: java.lang.IllegalStateException: Mapped class was not specified
4)修正代碼
RowMapper<Monster> rowMapper = new BeanPropertyRowMapper<>(Monster.class);
5)運行結果
11.查詢
id>=200
的 monster
并封裝到 Monster
實體對象
public class JdbcTemplateTest {/*** 查詢id>=200的monster并封裝到Monster實體對象*/@Testpublic void selectMulDataByJdbcTemplate() {//獲取到容器ApplicationContext ioc =new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");//獲取JdbcTemplate對象JdbcTemplate jdbcTemplate = ioc.getBean(JdbcTemplate.class);//1.確定API query//public <T> List<T> query(String sql, RowMapper<T> rowMapper, Object... args)//2.準備參數String sql = "SELECT id AS monsterId, `name`, skill FROM monster WHERE id >= ?";//這個?填進入也可以RowMapper<Monster> rowMapper = new BeanPropertyRowMapper<>(Monster.class);//3.調用List<Monster> monsterList = jdbcTemplate.query(sql, rowMapper, 200);//輸出for (Monster monster : monsterList) {System.out.println("monster=" + monster);}}
}
12.查詢返回結果只有一行一列的值, 比如查詢 id=100
的怪物名
public class JdbcTemplateTest {/*** 查詢返回結果只有一行一列的值*/@Testpublic void selectScalarByJdbcTemplate() {//獲取到容器ApplicationContext ioc =new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");//獲取JdbcTemplate對象JdbcTemplate jdbcTemplate = ioc.getBean(JdbcTemplate.class);//1.確定API query -> queryForObject//public <T> T queryForObject(String sql, Class<T> requiredType, @Nullable Object... args)//2.準備參數String sql = "SELECT `name` FROM monster WHERE id = ?";//Class<T> requiredType 表示你返回的單行單列的數據類型//3.調用String name = jdbcTemplate.queryForObject(sql, String.class, 100);//輸出System.out.println("name=" + name);System.out.println("ok~");}
}
13.使用 Map
傳入具名參數完成操作, 比如添加 螃蟹精 name
就是具名參數形式, 需要使用 NamedParameterJdbcTemplate
類
配置JdbcTemplate_ioc.xml
, 使用到NamedParameterJdbcTemplate
通過指定構造器配置bean 參考
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><!--配置NamedParameterJdbcTemplate對象--><bean class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate" id="namedParameterJdbcTemplate"><!--通過構造器, 設置數據源--><constructor-arg name="dataSource" ref="dataSource"/></bean>
</beans>
public class JdbcTemplateTest {/*** 使用Map傳入具名參數完成操作, 比如添加*/@Testpublic void testDataByNamedParameterJdbcTemplate() {//獲取到容器ApplicationContext ioc =new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");//得到NamedParameterJdbcTemplate beanNamedParameterJdbcTemplate namedParameterJdbcTemplate = ioc.getBean(NamedParameterJdbcTemplate.class);//1.確定API update//public int update(String sql, Map<String, ?> paramMap)//2.準備參數 [:my_id, :name, :skill] 要求按照規定的名字來設置參數String sql = "insert into monster values(:id, :name, :skill)";Map<String, Object> paramMap = new HashMap<>();//給paramMap填寫數據paramMap.put("id", 800);paramMap.put("name", "二郎神");paramMap.put("skill", "哮天犬");//3.調用int affected = namedParameterJdbcTemplate.update(sql, paramMap);//輸出System.out.println("add ok affected=" + affected);}
}
14.使用 sqlparametersource
來封裝具名參數, 還是添加一個 Monster
狐貍精
public class JdbcTemplateTest {/*** 使用sqlparamtersource 來封裝具名參數, 還是添加一個Monster*/@Testpublic void operDataBySqlparametersource() {//獲取到容器ApplicationContext ioc =new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");//得到NamedParameterJdbcTemplate beanNamedParameterJdbcTemplate namedParameterJdbcTemplate = ioc.getBean(NamedParameterJdbcTemplate.class);//1.確定API query//public int update(String sql, SqlParameterSource paramSource)//public BeanPropertySqlParameterSource(Object object)//2.準備參數String sql = "insert into monster values(:id, :name, :skill)";Monster monster = new Monster(900, "妲己", "魅惑");SqlParameterSource sqlParameterSource = new BeanPropertySqlParameterSource(monster);//3.調用int affected = namedParameterJdbcTemplate.update(sql, sqlParameterSource);//輸出System.out.println("add ok affected=" + affected);}
}
結果報錯 No value supplied for the SQL parameter 'id': Invalid property 'id' of bean class [com.zzw.spring.bean.Monster]: Bean property 'id' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
修改代碼
String sql = "insert into monster values(:monterId, :name, :skill)";
15.Dao 對象中使用 Jdbctemplate
完成對數據的操作
1)創建com.zzw.spring.jdbctemplate.dao.MonsterDao.java
@Repository //將MonsterDao注入到spring容器
public class MonsterDao {//注入一個屬性@Resourceprivate JdbcTemplate jdbcTemplate;//完成保存任務public void save(Monster monster) {//組織SQLString sql = "insert into monster values(?, ?, ?)";int affteced =jdbcTemplate.update(sql, monster.getMonsterId(), monster.getName(), monster.getSkill());System.out.println("affected=" + affteced);}
}
2)修改src/JdbcTemplate_ioc.xml
, 增加掃描配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><!--配置要掃描的包--><context:component-scan base-package="com.zzw.spring.jdbctemplate.dao"/><!--引入外部的jdbc.properties文件--><context:property-placeholder location="classpath:jdbc.properties"/><!--配置數據源對象-DataSource--><bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource"><!--給數據源對象配置屬性值--><property name="user" value="${jdbc.user}"/><property name="password" value="${jdbc.pwd}"/><property name="driverClass" value="${jdbc.driver}"/><property name="jdbcUrl" value="${jdbc.url}"/></bean><!--配置JdbcTemplate對象--><!--JdbcTemplate會使用到DataSource, 而DataSource可以拿到連接去操作數據庫--><bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate"><!--給JdbcTemplate對象配置dateSource--><property name="dataSource" ref="dataSource"/></bean><!--配置NamedParameterJdbcTemplate對象--><!--<bean class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate" id="namedParameterJdbcTemplate"><!–通過構造器, 設置數據源–><constructor-arg name="dataSource" ref="dataSource"/></bean>-->
</beans>
3)修改JdbcTemplateTest.java
, 增加測試方法
public class JdbcTemplateTest {//測試MonsterDao是否生效@Testpublic void monsterDaoSave() {//獲取到容器ApplicationContext ioc =new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");MonsterDao monsterDao = ioc.getBean(MonsterDao.class);monsterDao.save(new Monster(1000, "女媧", "女媧補天"));System.out.println("save ok~");}
}