目录
JdbcTemplate
需求
官方文档
JdbcTemplate-基本介绍
JdbcTemplate 使用实例
需求说明
创建数据库 spring 和表 monster
创建配置文件 src/jdbc.properties
创建配置文件 src/JdbcTemplate_ioc.xml
创建类JdbcTemplateTest测试是否可以正确得到数据源
配置 JdbcTemplate_ioc.xml,将数据源分配给 JdbcTemplate bean
创建和数据库对应的字段类
1. 修改 JdbcTemplateTest.java,添加一个新的 monster
2. 修改 JdbcTemplateTest.java,更新一个 monster 的 skill
3.修改 JdbcTemplateTest.java,批量添加二个 monster 白蛇精和青
4.查询 id=100 的 monster 并封装到并封装到Monster实体对象[在实际开发中,非常有用]
5.查询id>=200的monster并封装到Monster实体对象
6.查询返回结果只有一行一列的值,比如查询id=100的怪物名
7.使用Map传入具名参数完成操作,比如添加 螃蟹精.:name 就是具名参数形式需要使用NamedParameterJdbcTemplate 类
修改JdbcTemplate_ioc.xml, 增加配置
开始测试
8.使用sqlparametersoruce 来封装具名参数,还是添加一个Monster 狐狸精
9.Dao 对象中使用 JdbcTemplate 完成对数据操作
创建MonsterDao类
修改JdbcTemplate_ioc.xml, 增加配置
测试
JdbcTemplate
需求
=如果程序员就希望使用 spring 框架来做项目,spring 框架如何处理对数据库的操作呢?
方案 1. 使用前面做项目开发的 JdbcUtils 类
方案 2. 其实 spring 提供了一个操作数据库(表)功能强大的类 JdbcTemplate 。我们可以同ioc 容器来配置一个 jdbcTemplate 对象,使用它来完成对数据库表的各种操作.
官方文档
JdbcTemplate APIs : /spring-framework-5.3.8/docs/javadoc-api/index.html
JdbcTemplate-基本介绍
● 基本介绍
1. 通过 Spring 可以配置数据源,从而完成对数据表的操作
2. JdbcTemplate 是 Spring 提供的访问数据库的技术。可以将 JDBC 的常用操作封装为模板方法。[JdbcTemplate 类图].
JdbcTemplate 使用实例
需求说明
我们使用 spring 的方式来完成 JdbcTemplate 配置和使用JdbcTemplate 使用-代码演示
引入使用 JdbcTemplate 需要的 jar 包
创建数据库 spring 和表 monster
-- 创建数据库
CREATE DATABASE spring
USE spring
-- 创建表 monster
CREATE TABLE monster(
id INT PRIMARY KEY, `name` VARCHAR(64) NOT NULL DEFAULT '',
韩顺平 Java 工程师
skill VARCHAR(64) NOT NULL DEFAULT '' )CHARSET=utf8
INSERT INTO monster VALUES(100, '青牛怪', '吐火');
INSERT INTO monster VALUES(200, '黄袍怪', '吐烟');
INSERT INTO monster VALUES(300, '蜘蛛怪', '吐丝');
创建配置文件 src/jdbc.properties
jdbc.user=root
jdbc.pwd=你的数据库密码
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:你的数据库端口/数据库名字例如我的
jdbc.user=root
jdbc.pwd=xxxx
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
创建配置文件 src/JdbcTemplate_ioc.xml
<!--引入外部的jdbc.properties文件--><context:property-placeholder location="classpath:jdbc.properties"/><!--配置数据源对象-DataSoruce--><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>
创建类JdbcTemplateTest测试是否可以正确得到数据源
@Testpublic void testDatasourceByJdbcTemplate() throws SQLException {//获取到容器ApplicationContext ioc =new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");DataSource dataSource = ioc.getBean(DataSource.class);Connection connection = dataSource.getConnection();System.out.println("获取到connection= " + connection);connection.close();System.out.println("ok");}
配置 JdbcTemplate_ioc.xml,将数据源分配给 JdbcTemplate bean
<!--引入外部的jdbc.properties文件--><context:property-placeholder location="classpath:jdbc.properties"/><!--配置数据源对象-DataSoruce--><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对象--><bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate"><!--给JdbcTemplate对象配置dataSource--><property name="dataSource" ref="dataSource"/></bean>
创建和数据库对应的字段类
public class Monster {private Integer monsterId;private String name;private String skill;//全参构造器public Monster(Integer monsterId, String name, String skill) {this.monsterId = monsterId;this.name = name;this.skill = skill;}//无参构造器一定要写,Spring反射创建对象时,需要使用public Monster() {}public Integer getMonsterId() {return monsterId;}public void setMonsterId(Integer monsterId) {this.monsterId = monsterId;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSkill() {return skill;}public void setSkill(String skill) {this.skill = skill;}@Overridepublic String toString() {return "Monster{" +"monsterId=" + monsterId +", name='" + name + '\'' +", skill='" + skill + '\'' +'}';}
}
1. 修改 JdbcTemplateTest.java,添加一个新的 monster
@Testpublic void addDataByJdbcTemplate() {//获取到容器ApplicationContext ioc =new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");//获取JdbcTemplate对象JdbcTemplate jdbcTemplate = ioc.getBean(JdbcTemplate.class);//1. 添加方式1//String sql = "INSERT INTO monster VALUES(400, '红孩儿', '枪法')";//jdbcTemplate.execute(sql);//2. 添加方式2String sql = "INSERT INTO monster VALUES(?, ?, ?)";//affected表示 执行后表受影响的记录数int affected = jdbcTemplate.update(sql, 500, "红孩儿2", "枪法2");System.out.println("add ok affected=" + affected);}
2. 修改 JdbcTemplateTest.java,更新一个 monster 的 skill
@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=?";int affected = jdbcTemplate.update(sql, "美女计", 300);System.out.println("update ok affected= " + affected);}
3.修改 JdbcTemplateTest.java,批量添加二个 monster 白蛇精和青
1. 对于某个类, 有很多API, 使用的步骤
2. 使用技巧
(1) 先确定API名字
(2) 根据API提供相应的参数 [组织参数]
(3) 把自己的调用思路清晰
(4) 根据API, 可以推测类似的用法和功能
//批量添加二个monster 白蛇精和青蛇精@Testpublic void addBatchDataByJdbcTemplate() {ApplicationContext ioc = new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");//得到JdbcTemplate beanJdbcTemplate jdbcTemplate = ioc.getBean(JdbcTemplate.class);//添加..//1. 先确定,猜测API名称 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..");}
4.查询 id=100 的 monster 并封装到并封装到Monster实体对象[在实际开发中,非常有用]
public void selectDataByJdbcTemplate() {ApplicationContext ioc = new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");//得到JdbcTemplate beanJdbcTemplate jdbcTemplate = ioc.getBean(JdbcTemplate.class);//组织SQL//通过BeanPropertyRowMapper获取rowmapper 是一个接口,可以将查询的结果,封装到你指定的Monster对象中.//1. 确定API : 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 = 100";//使用RowMapper 接口来对返回的数据,进行一个封装-》底层使用的反射->setter//这里有一个细节: 你查询的记录的表的字段需要和 Monster的对象字段名保持一致RowMapper<Monster> rowMapper = new BeanPropertyRowMapper<>(Monster.class);//jdbcTemplateMonster monster = jdbcTemplate.queryForObject(sql, rowMapper);System.out.println("monster= " + monster);System.out.println("查询ok");}
5.查询id>=200的monster并封装到Monster实体对象
注意因为配置的对应类的id是 monsterId
所以我们在使用的过程中需要用monsterId 这就是为什么要取一个别名。
通过BeanPropertyRowMapper获取rowmapper 是一个接口,可以将查询的结果,封装到你指定的Monster对象中.
@Testpublic void selectMulDataByJdbcTemplate() {ApplicationContext ioc =new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");//得到JdbcTemplate beanJdbcTemplate jdbcTemplate = ioc.getBean(JdbcTemplate.class);//组织SQL//通过BeanPropertyRowMapper获取rowmapper 是一个接口,可以将查询的结果,封装到你指定的Monster对象中.//1. 确定API//public <T> 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, 100);for (Monster monster : monsterList) {System.out.println("monster= " + monster);}}
6.查询返回结果只有一行一列的值,比如查询id=100的怪物名
/*** 查询返回结果只有一行一列的值*/@Testpublic void selectScalarByJdbcTemplate() {ApplicationContext ioc =new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");//得到JdbcTemplate beanJdbcTemplate jdbcTemplate = ioc.getBean(JdbcTemplate.class);//1. 确定API//public <T> T queryForObject(String sql, Class<T> requiredType)//2. 提供参数String sql = "SELECT NAME FROM monster WHERE id = 100";//Class<T> requiredType 表示你返回的单行单列的数据类型String name =jdbcTemplate.queryForObject(sql, String.class);System.out.println("返回name= " + name);}
7.使用Map传入具名参数完成操作,比如添加 螃蟹精.:name 就是具名参数形式需要使用NamedParameterJdbcTemplate 类
修改JdbcTemplate_ioc.xml, 增加配置
<!--引入外部的jdbc.properties文件--><context:property-placeholder location="classpath:jdbc.properties"/><!--配置数据源对象-DataSoruce--><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对象--><bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate"><!--给JdbcTemplate对象配置dataSource--><property name="dataSource" ref="dataSource"/></bean><!--配置NamedParameterJdbcTemplate对象--><bean class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"id="namedParameterJdbcTemplate"><!--通过构造器,设置数据源--><constructor-arg name="dataSource" ref="dataSource"/></bean>
开始测试
@Testpublic void testDataByNamedParameterJdbcTemplate() {ApplicationContext ioc =new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");//得到NamedParameterJdbcTemplate beanNamedParameterJdbcTemplate namedParameterJdbcTemplate =ioc.getBean(NamedParameterJdbcTemplate.class);//1. 确定使用API//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);}
8.使用sqlparametersoruce 来封装具名参数,还是添加一个Monster 狐狸精
@Testpublic void operDataBySqlparametersoruce() {ApplicationContext ioc =new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");//得到NamedParameterJdbcTemplate beanNamedParameterJdbcTemplate namedParameterJdbcTemplate =ioc.getBean(NamedParameterJdbcTemplate.class);//确定API//public int update(String sql, SqlParameterSource paramSource)//public BeanPropertySqlParameterSource(Object object)//准备参数String sql = "INSERT INTO monster VALUES(:monsterId, :name, :skill)";Monster monster = new Monster(900, "大象精", "搬运木头");SqlParameterSource sqlParameterSource =new BeanPropertySqlParameterSource(monster);//调用int affected =namedParameterJdbcTemplate.update(sql, sqlParameterSource);System.out.println("add ok affected= " + affected);}
9.Dao 对象中使用 JdbcTemplate 完成对数据操作
创建MonsterDao类
@Repository //将MonsterDao 注入到spring容器
public class MonsterDao {//注入一个属性@Resourceprivate JdbcTemplate jdbcTemplate;//完成保存任务public void save(Monster monster) {//组织sqlString sql = "INSERT INTO monster VALUES(?,?,?)";int affected = jdbcTemplate.update(sql, monster.getMonsterId(), monster.getName(), monster.getSkill());System.out.println("affected= " + affected);}
}
修改JdbcTemplate_ioc.xml, 增加配置
<!--配置要扫描包--><context:component-scanbase-package="com.spring.jdbctemplate.dao"/><!--引入外部的jdbc.properties文件--><context:property-placeholder location="classpath:jdbc.properties"/><!--配置数据源对象-DataSoruce--><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对象--><bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate"><!--给JdbcTemplate对象配置dataSource--><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>
测试
//测试MonsterDAO@Testpublic void monsterDaoSave() {ApplicationContext ioc =new ClassPathXmlApplicationContext("JdbcTemplate_ioc.xml");MonsterDao monsterDao = ioc.getBean(MonsterDao.class);Monster monster = new Monster(1000, "小鸭精", "吃鱼");monsterDao.save(monster);System.out.println("MonsterDAO保存 ok ..");}