目录
十三、JdbcTemplate
13.1环境准备
13.2新增
13.3修改
13.4删除
13.5查询
13.6查询一个值
13.7批量添加
13.8批量修改
13.9批量删除
13.10使用回调函数
13.11使用德鲁伊连接池
十三、JdbcTemplate
-
JdbcTemplate是Spring提供的一个JDBC模板类,是对JDBC的封装,简化JDBC代码。
-
当然,也可以让Spring集成其它的ORM框架,例如:MyBatis、Hibernate等。
13.1环境准备
数据库表:t_user
引入相关依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!--spring jdbc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>6.0.3</version>
</dependency>
</dependencies>
准备实体类:表t_user对应的实体类User
package com.hhb.bean;
public class User {
private Integer id;
private String realName;
private Integer age;
public User(Integer id, String realName, Integer age) {
this.id = id;
this.realName = realName;
this.age = age;
}
public User() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", realName='" + realName + '\'' +
", age=" + age +
'}';
}
}
手写数据源
package com.hhb.bean;
import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.*;
import java.util.logging.Logger;
//自己的数据源。数据源存在的目的是为了提供Connection对象。
//只要实现了DataSource接口的都是数据源
//德鲁伊连接池、c3p0连接池、dbcp连接池都实现了DataSource接口。
public class MyDataSource implements DataSource {
private String driver;
private String url;
private String username;
private String password;
public void setDriver(String driver) {
this.driver = driver;
}
public void setUrl(String url) {
this.url = url;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public Connection getConnection() throws SQLException {
try {
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, username, password);
return connection;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return null;
}
@Override
public PrintWriter getLogWriter() throws SQLException {
return null;
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
}
@Override
public int getLoginTimeout() throws SQLException {
return 0;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
}
编写Spring配置文件
<?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">
<!--配置自己写的数据源-->
<!--也可以集成其他人或者其它组织开发的数据源,例如:c3p0 dbcp druid-->
<bean id="ds" class="com.hhb.bean.MyDataSource">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring6"/>
<property name="username" value="root"/>
<property name="password" value="030522"/>
</bean>
<bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"/>
</bean>
</beans>
13.2新增
@Test
public void testInsert(){
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("JdbcTemplate", JdbcTemplate.class);
String sql="insert into t_user(real_name,age) values(?,?)";
int count = jdbcTemplate.update(sql, "王五", 23);
System.out.println(count);
}
-
update方法有两个参数:
-
第一个参数:要执行的SQL语句。
-
第二个参数:可变长参数,参数的个数可以是0个,也可以是多个。一般是SQL语句中有几个问号,则对应几个参数。
-
13.3修改
@Test
public void testUpdate() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("JdbcTemplate", JdbcTemplate.class);
String sql = "update t_user set real_name=? , age=? where id =?";
int count = jdbcTemplate.update(sql, "张二", 25, 1);
System.out.println(count);
}
13.4删除
@Test
public void testDelete() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("JdbcTemplate", JdbcTemplate.class);
String sql = "delete from t_user where id =?";
int count = jdbcTemplate.update(sql, 1);
System.out.println(count);
}
13.5查询
查询单条记录
@Test
public void testSelectOne(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("JdbcTemplate", JdbcTemplate.class);
String sql="select id,real_name,age from t_user where id=?";
User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), 4);
System.out.println(user);
}
-
queryForObject方法三个参数
-
第一个参数:sql语句
-
第二个参数:Bean属性值和数据库记录行的映射对象。在构造方法中指定映射的对象类型。
-
第三个参数:可变长参数,给sql语句的占位符问号传值。
-
查询多条记录
@Test
public void testSelectAll(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("JdbcTemplate", JdbcTemplate.class);
String sql="select id,real_name,age from t_user";
List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
System.out.println(users);
}
13.6查询一个值
@Test
public void testSelectOneValue() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("JdbcTemplate", JdbcTemplate.class);
String sql = "select count(1) from t_user";//返回总记录条数是一个数字
Integer count = jdbcTemplate.queryForObject(sql, int.class);
System.out.println(count);
}
13.7批量添加
@Test
public void testBatchInsert() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("JdbcTemplate", JdbcTemplate.class);
String sql = "insert into t_user(real_name,age) values(?,?)";
//准备数据
Object[] obj1 = {"小明", 25};
Object[] obj2 = {"小红", 26};
Object[] obj3 = {"小亮", 27};
Object[] obj4 = {"小花", 28};
//添加到List集合
ArrayList<Object[]> list = new ArrayList<>();
list.add(obj1);
list.add(obj2);
list.add(obj3);
list.add(obj4);
//执行sql语句
int[] count = jdbcTemplate.batchUpdate(sql, list);
System.out.println(Arrays.toString(count));
}
13.8批量修改
@Test
public void testBatchUpdate() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("JdbcTemplate", JdbcTemplate.class);
String sql = "update t_user set real_name=?,age=? where id=?";
//准备数据
Object[] obj1 = {"小张", 22, 5};
Object[] obj2 = {"小李", 23, 6};
Object[] obj3 = {"小王", 24, 7};
Object[] obj4 = {"小赵", 25, 8};
//添加到List集合
ArrayList<Object[]> list = new ArrayList<>();
list.add(obj1);
list.add(obj2);
list.add(obj3);
list.add(obj4);
//执行SQL语句
int[] count = jdbcTemplate.batchUpdate(sql, list);
System.out.println(Arrays.toString(count));
}
13.9批量删除
@Test
public void testBetchDelete(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("JdbcTemplate", JdbcTemplate.class);
String sql="delete from t_user where id=?";
Object[] obj1={9};
Object[] obj2={10};
Object[] obj3={11};
Object[] obj4={12};
ArrayList<Object[]> list = new ArrayList<>();
list.add(obj1);
list.add(obj2);
list.add(obj3);
list.add(obj4);
int[] count = jdbcTemplate.batchUpdate(sql, list);
System.out.println(Arrays.toString(count));
}
13.10使用回调函数
@Test
public void testCallBack() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("JdbcTemplate", JdbcTemplate.class);
String sql = "select * from t_user where id=?";
//注册回调函数,当execute方法执行的时候,回调函数中的PreparedStatementCallback()会被调用
User user = jdbcTemplate.execute(sql, new PreparedStatementCallback<User>() {
@Override
public User doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
User user = null;
ps.setInt(1, 2);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
int id = rs.getInt("id");
String realName = rs.getString("real_name");
int age = rs.getInt("age");
user = new User(id, realName, age);
}
return user;
}
});
System.out.println(user);
}
13.11使用德鲁伊连接池
-
之前数据源是自己手写的,也可以使用别人写好的。例如德鲁伊连接池。
第一步:引入德鲁伊连接池的依赖
<!--引入druid依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
第二步:将德鲁伊中的数据源配置到spring配置文件中
<bean id="ds" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring6"/>
<property name="username" value="root"/>
<property name="password" value="030522"/>
</bean>
<bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"/>
</bean>
测试结果