Spring JDBCTemplate
1.介绍
Spring框架对JDBC的简单封装。提供了一个JDBCTemplate对象简化JDBC的开发
它是Spring框架中提供的一个对象,是对原始繁琐的jdbc API对象的简单封装。Spring框架为我们提供了很多操作模板类。例如:操作关系型数据的Jdbc Template和Hibernate Template,操作nosql数据库的Redis Template,操作消息队列Jms Template
步骤:
(1)导入jar包
推荐一个网址,可以下载到想要的jar包:https://mvnrepository.com/
(2)创建JdbcTemplate对象。依赖于数据源DataSource
JdbcTemplate template = new JdbcTemplate(ds);
(3)调用JdbcTemplate 的方法来完成CRUD的操作
* update():执行DML语句。增删改语句
* queryForMap():查询结果将结果集封装为map集合,注意:这个方法查询的结果集长度只能为1(即只能有一条记录),将列名作为key,值作为value,将这条记录封装为一个map集合
* queryForList():查询结果将结果集封装为List集合,注意:将每一条记录封装为一个Map集合,再将Map集合装在到List集合中
* query():查询结果,将结果封装为JavaBean对象
query参数:RowMapper
一般我们使用BeanPropertyRowMapper实现类。可以完成数据到JavaBean的字段封装
new BeanPropertyRowMapper<类型>(类型.class)
自动看属性,和数据库的字段名,如果匹配,就会把值拿出来装到对应的set里面取
* queryForObject:查询结果,将结果封装为对象
一般用于聚合函数的查询
2.JdbcTemplate使用
第一个入门JdbcTemplate程序
package cn.company.datasource.jdbctemplate; import cn.company.datasource.utils.JDBCUtils; import org.springframework.jdbc.core.JdbcTemplate; public class JdbcTemplateDemo01 { public static void main(String[] args) { // 1.导入jar包 // 2.创建JDBCTemplate对象 JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource()); // 3.调用方法 String sql = "update users set name='zhaoliu' where id=?"; int update = jdbcTemplate.update(sql, 4); System.out.println(update); } }
3.练习
需求:
(1)修改1号数据的password为444555
(2)添加一条记录
(3)删除刚才添加的记录
(4)查询id为1的记录,将其封装为Map集合
(5)查询所有记录,将其封装为List
(6)查询所有记录,将其封装为Emp对象的List集合
(7)查询总记录数
Emp.java
package cn.company.domain; import java.sql.Date; public class Emp { private Integer id; private String name; private String password; private String email; private Date birthday; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public String toString() { return "Emp{" + "id=" + id + ", name='" + name + '\'' + ", password='" + password + '\'' + ", email='" + email + '\'' + ", birthday=" + birthday + '}'; } }
JdbcTemplateDemo2.java
package cn.company.datasource.jdbctemplate; import cn.company.datasource.utils.JDBCUtils; import cn.company.domain.Emp; import org.junit.Test; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import java.sql.Date; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Map; public class JdbcTemplateDemo2 { //使用Junit单元测试,可以让方法独立执行 // 创建JDBCTemplate对象 private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource()); /** * (1)修改1号数据的password为444555 */ @Test public void test1() { String sql = "update users set password=444555 where id=?"; int update1 = jdbcTemplate.update(sql, 1); System.out.println(update1); } /** * (2)添加一条记录 */ @Test public void test2() { String sql = "insert into users(id,name,password,email,birthday) values(?,?,?,?,?)"; int update2 = jdbcTemplate.update(sql, 5, "guojing", "333333", "123456@qq.com", "1999-12-17"); System.out.println(update2); } /** * (3)删除刚才添加的记录 */ @Test public void test3() { String sql = "delete from users where id=?"; int update3 = jdbcTemplate.update(sql, 5); System.out.println(update3); } /** * (4)查询id为1的记录,将其封装为Map集合 * 注意:这个方法,查询的结果集长度只能为1 */ @Test public void test4() { String sql = "select * from users where id=?"; Map<String, Object> stringObjectMap = jdbcTemplate.queryForMap(sql, 1); System.out.println(stringObjectMap); } /** * (5)查询所有记录,将其封装为List */ @Test public void test5() { String sql = "select * from users where id=? or id=?"; List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql, 1, 5); System.out.println(mapList); for (Map<String, Object> stringObjectMap : mapList) { System.out.println(stringObjectMap); } } /** * (6)查询所有记录,将其封装为Emp对象(JavaBean对象)的List集合 */ @Test public void test6() { String sql = "select * from users"; List<Emp> list = jdbcTemplate.query(sql, new RowMapper<Emp>() { @Override public Emp mapRow(ResultSet resultSet, int i) throws SQLException { Emp emp = new Emp(); int id = resultSet.getInt("id"); String name = resultSet.getString("name"); String password = resultSet.getString("password"); String email = resultSet.getString("email"); Date birthday = resultSet.getDate("birthday"); emp.setId(id); emp.setName(name); emp.setPassword(password); emp.setEmail(email); emp.setBirthday(birthday); return emp; } }); for (Emp emp : list) { System.out.println(emp); } } /** * (6)查询所有记录,将其封装为Emp对象(JavaBean对象)的List集合 * BeanPropertyRowMapper已经实现了RowMapper接口了 */ @Test public void test6_2() { String sql = "select * from users"; List<Emp> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class)); for (Emp emp : list) { System.out.println(emp); } } /** * (7)查询总记录数 */ @Test public void test7() { String sql = "select count(id) from users"; Long aLong = jdbcTemplate.queryForObject(sql, Long.class); System.out.println(aLong); } }
4.新的开发步骤(不用导入jar包,通过在pom.xml中导入坐标的方式)
(1)导入spring-jdbc(因为底层封装了JdbcTemplate)和spring-tx坐标(因为底层用到了事务)(pom.xml中)
(2)创建数据库表和实体
(3)创建JdbcTemplate对象
(4)执行数据库操作
案例:
(1)在pom.xml中导入spring-jdbc和spring-tx
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>spring_jdbc</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.2.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.2.9.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.4</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.44</version> </dependency> </dependencies> </project>
(2)创建数据库表
CREATE DATABASE test CHARACTER SET utf8 COLLATE utf8_estonian_ci; USE test; CREATE TABLE `account` ( `name` VARCHAR(40) NOT NULL , `money` INT NOT NULL, primary key (`name`) ) ENGINE = INNODB DEFAULT charset = utf8;
修改money的字段类型
alter table account modify column money double;
创建实体
package com.company.domain; public class Account { private String name; private double money; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } @Override public String toString() { return "Account{" + "name='" + name + '\'' + ", money=" + money + '}'; } }
(3)创建JdbcTemplate对象
(4)执行数据库操作
JdbcTemplateTest.java
package com.company.test; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.junit.Test; import org.springframework.jdbc.core.JdbcTemplate; import java.beans.PropertyVetoException; public class JdbcTemplateTest { // 测试JdbcTemplate开发步骤 @Test public void test1() throws PropertyVetoException { // 创建数据源对象 ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setDriverClass("com.mysql.jdbc.Driver"); cpds.setJdbcUrl("jdbc:mysql://localhost:3306/test"); cpds.setUser("root"); cpds.setPassword("123456"); JdbcTemplate jdbcTemplate = new JdbcTemplate(); // 设置数据源对象,知道数据库在哪 jdbcTemplate.setDataSource(cpds); // 执行操作 int row = jdbcTemplate.update("insert into account values (?,?)", "tom", 5000); System.out.println(row); } }
5.Spring产生JdbcTemplate对象
我们可以将JdbcTemplate的创建权交给Spring,将DataSource的创建权也交给Spring,在Spring容器内部将数据源DataSource注入到JdbcTemplate模板对象中,配置如下:
这样我们直接可以getBean()获取对象JdbcTemplate实例了
完整版代码
pom.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--数据源DataSource--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/> <property name="user" value="root"/> <property name="password" value="123456"/> </bean> <!--JdbcTemplate模板对象--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> </beans>
JdbcTemplateTest.java
package com.company.test; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import java.beans.PropertyVetoException; public class JdbcTemplateTest { @Test // 测试Spring产生JdbcTemplate对象 public void test() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); JdbcTemplate jdbcTemplate = applicationContext.getBean(JdbcTemplate.class); int update = jdbcTemplate.update("insert into account values (?, ?)", "zhangsan", 2000); System.out.println(update); } }
再优化
将applicationContext.xml中数据源DataSource中的property抽取出来放到jdbc.properties中
完整版
pom.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 http://www.springframework.org/schema/context/spring-context.xsd "> <!-- 加载jdbc.properties--> <context:property-placeholder location="jdbc.properties"/> <!--数据源DataSource--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.user}}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--JdbcTemplate模板对象--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> </beans>
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.user=root jdbc.password=123456
6.案例
package com.company.test; import com.company.domain.Account; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class JdbcTemplateCRUDTest { // 测试谁,就注入谁 @Autowired private JdbcTemplate jdbcTemplate; @Test public void testUpdate() { jdbcTemplate.update("update account set money=? where name=?", 10000, "tom"); } @Test public void testQuery() { List<Account> accountList = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class)); System.out.println(accountList); } // 查询单个,如果是一个返回的是一个实体对象,需要new一个BeanPropertyRowMapper进行映射 @Test public void testQueryOne() { Account account = jdbcTemplate.queryForObject("select * from account where name=?", new BeanPropertyRowMapper<Account>(Account.class), "tom"); System.out.println(account); } // 聚合查询,查询总数。如果返回的是一个简单的类型,不用再用BeanPropertyRowMapper映射 @Test public void testQueryCount() { Long aLong = jdbcTemplate.queryForObject("select count(*) from account", Long.class); System.out.println(aLong); } }
由于前面已经设置了打印出来的格式,所以对于上面代码acountList和account打印出来的格式,就如下面这样了。
acountList
acount
总结: