一、JdbcTemplate环境搭建
Spring JDBC Template 是Spring 操作数据库的模块, 基于 JDBC API
在数据库中创建表porsche
代码语言:javascript复制SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for porsche
-- ----------------------------
DROP TABLE IF EXISTS `porsche`;
CREATE TABLE `porsche` (
`porsche_id` int(11) NOT NULL AUTO_INCREMENT,
`name` char(100) DEFAULT NULL,
`price` double DEFAULT NULL,
PRIMARY KEY (`porsche_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=gb2312;
-- ----------------------------
-- Records of porsche
-- ----------------------------
BEGIN;
INSERT INTO `porsche` VALUES (1, 'Panamera', 970000);
INSERT INTO `porsche` VALUES (2, 'Cayenne', 910000);
INSERT INTO `porsche` VALUES (3, 'Macan', 550000);
INSERT INTO `porsche` VALUES (4, 'Taycan', 880000);
INSERT INTO `porsche` VALUES (5, 'Porsche 911', 1270000);
INSERT INTO `porsche` VALUES (6, 'Porsche 718', 540000);
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
创建一个maven项目spring-jdbc-template,导入spring,mysql,druid依赖
代码语言:javascript复制<properties>
<spring-version>5.3.13</spring-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring-version}</version>
</dependency>
<!--spring jdbc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.14</version>
</dependency>
</dependencies>
resources目录下创建数据库信息配置文件datasource.properties
代码语言:javascript复制driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
username=root
password=root
initialSize=5
maxActive=20
创建application.xml,配置数据库连接池及Spring JDBC Template
代码语言:javascript复制<?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:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.3.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--引用外部配置文件-->
<context:property-placeholder location="classpath:database.properties"></context:property-placeholder>
<!--数据库连接池配置-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}" />
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
<property name="initialSize" value="${initialSize}"/>
<property name="maxActive" value="${maxActive}"/>
</bean>
<!--配置JDBC Template,注入Spring容器中-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
</bean>
</beans>
在test包下创建ApplicationTest,使用Spring Test测试IoC容器中数据源及JDBC Template
代码语言:javascript复制@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application.xml")
public class ApplicationTest {
@Autowired
private DruidDataSource dataSource;
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void testDataSource() throws SQLException {
System.out.println(dataSource);
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
@Test
public void testJdbcTemplate(){
System.out.println(jdbcTemplate);
}
}
执行测试类
容器中成功创建了dataSource数据源及jdbcTemplate
二、JdbcTemplate实现增删改查
新建一个测试类PorscheTest继承ApplicationTest
代码语言:javascript复制public class PorscheTest extends ApplicationTest {
@Autowired
private JdbcTemplate jdbcTemplate;
}
更新porsche_id=4的name为Taycan 2022
增加测试方法
代码语言:javascript复制@Test
public void testUpdateName(){
String updateNameSql = "UPDATE porsche SET name=? WHERE porsche_id=?";
int count = jdbcTemplate.update(updateNameSql, "Taycay 2022", 4);
System.out.println("Affected rows:" count);
}
执行该方法,影响了一行,更新成功
批量插入数据
增加测试方法
代码语言:javascript复制@Test
public void testBatchInsert(){
String batchInsertSql = "insert into `porsche`(`name`,`price`) values (?,?)";
// List的长度就是sql要执行的次数,每一个数组表示每一次执行用到的参数
List<Object[]> batchData = new ArrayList<>();
batchData.add(new Object[]{"918 Spyder",13380000});
batchData.add(new Object[]{"Cayman",720000});
batchData.add(new Object[]{"Boxster",670000});
batchData.add(new Object[]{"Carrera GT",6450000});
int[] countList = jdbcTemplate.batchUpdate(batchInsertSql, batchData);
System.out.println("Affected rows:" Arrays.toString(countList));
}
执行测试方法,四条SQL插入语句全部执行成功
将查询到的单条记录转换成Java对象
首先新建一个entity包,并增加一个实体类Porsche,属性与数据库字段一致,如果字段名不一致可以使用别名来保持一致
代码语言:javascript复制public class Porsche {
private Integer id;
private String name;
private Double price;
// 此处省略getter/setter/toString方法
}
增加测试方法
代码语言:javascript复制@Test
public void testFindOneTransfer2JavaBean(){
String findOneSql = "SELECT porsche_id id, name, price FROM porsche WHERE porsche_id=?";
// RowMapper,定义每一行记录和Java Bean如何映射
RowMapper rowMapper = new BeanPropertyRowMapper(Porsche.class);
Porsche taycan = (Porsche) jdbcTemplate.queryForObject(findOneSql, rowMapper, 4);
System.out.println(taycan);
}
要注意的点:
执行测试,成功输出JavaBean
如果查询不到记录就会报错,可以使用try catch来包裹
将查询到的多条记录封装成List
增加测试方法
代码语言:javascript复制@Test
public void testFindListTransfer2ArrayList(){
String findListSql = "SELECT porsche_id id, name, price FROM porsche WHERE price >=?";
// 要使用List形式的rowMapper
RowMapper rowMapper = new BeanPropertyRowMapper<>(Porsche.class);
List<Porsche> porsches = jdbcTemplate.query(findListSql, rowMapper, 500000);
System.out.println(porsches);
}
执行测试
查询price最大的一条记录
增加测试方法
代码语言:javascript复制@Test
public void testFindMaxPrice(){
String findMaxPriceSql = "SELECT MAX(price) FROM porsche";
// 基本数据类型的包装类可以直接使用包装类的class,自定义的类需要new BeanPropertyRowMapper
Double maxPrice = jdbcTemplate.queryForObject(findMaxPriceSql, Double.class);
System.out.println(maxPrice);
}
执行测试方法
具名参数的SQL语句插入数据,多个参数以Map传递
由于使用❓作为占位符必须要保持参数的顺序,因此可以使用变量名代替SQL语句参数中的占位符,使用具名参数要使用到NamedParameterJdbcTemplate
xml中配置一个NamedParameterJdbcTemplate
代码语言:javascript复制<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
</bean>
增加测试方法
代码语言:javascript复制@Test
public void insertByNamedParameter(){
String insertSqlNamedParameter = "INSERT INTO porsche(name,price) VALUES(:name,:price)";
Map namedParameter = new HashMap<>();
namedParameter.put("name","Taycan Tubo S");
namedParameter.put("price",880000);
int count = namedParameterJdbcTemplate.update(insertSqlNamedParameter, namedParameter);
System.out.println("Affected rows:" count);
}
执行测试
以sqlParameter形式传递参数插入数据
增加测试方法
代码语言:javascript复制@Test
public void insertByJavaBeanParameter(){
String insertSqlByJavaBeanParameter = "INSERT INTO porsche(name,price) VALUES(:name,:price)";
Porsche porsche = new Porsche();
porsche.setName("Taycan 2023");
porsche.setPrice(880000.0);
BeanPropertySqlParameterSource beanPropertySqlParameterSource = new BeanPropertySqlParameterSource(porsche);
int count = namedParameterJdbcTemplate.update(insertSqlByJavaBeanParameter, beanPropertySqlParameterSource);
System.out.println("Affected rows:" count);
}
执行测试
至此,Spring JdbcTemplate模块完结