目录
十三、JdbcTemplate
13.1环境准备
13.2新增
13.3修改
13.4删除
13.5查询
13.6查询一个值
13.7批量添加
13.8批量修改
13.9批量删除
13.10使用回调函数
13.11使用德鲁伊连接池
JdbcTemplate是Spring提供的一个JDBC模板类,是对JDBC的封装,简化JDBC代码。
当然,也可以让Spring集成其它的ORM框架,例如:MyBatis、Hibernate等。
数据库表:t_user
引入相关依赖
org.springframework
spring-context
6.0.3
mysql
mysql-connector-java
8.0.31
junit
junit
4.13.2
test
org.springframework
spring-jdbc
6.0.3
准备实体类:表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 unwrap(Class iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class> iface) throws SQLException {
return false;
}
}
编写Spring配置文件
@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语句中有几个问号,则对应几个参数。
@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);
}
@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);
}
查询单条记录
@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 users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
System.out.println(users);
}
@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);
}
@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
@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
@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
@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() {
@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);
}
之前数据源是自己手写的,也可以使用别人写好的。例如德鲁伊连接池。
第一步:引入德鲁伊连接池的依赖
com.alibaba
druid
1.1.12
第二步:将德鲁伊中的数据源配置到spring配置文件中
测试结果