Spring JdbcTemplate的常用方法

简单记录-Java EE企业级应用开发教程(Spring+Spring MVC+MyBatis)-Spring的数据库开发

在JdbcTemplate类中,提供了大量的更新和查询数据库的方法,我们就是使用这些方法来操作数据库的。

execute()

execute()

execute(String sql)方法可用于执行sql语句

下面就以创建数据表的SQL语言为例,来说明。

(1)在MySQL中,创建一个名为spring的数据库,创建方式如图所示

在图中,首先使用SQL语句创建了数据库spring(create database spring;),然后选择使用spring数据库(use spring;)。

然后再查看数据库中的表,其结果显示为空。(show tables;)

(2)在Idea中,在JavaEE-enterprise-application-development-tutorial项目里,创建一个名为chapter04的Maven项目module

<?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>com.awen</groupId>
<artifactId>JavaEE-enterprise-application-development-tutorial</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>chapter01</module>
<module>chapter02</module>
<module>chapter04</module>
</modules> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
</project>

会自动下载导入对应的依赖项。

(3)在在src/main/resources目录下,创建Spring的配置文件applicationContext.xml,在该文件中配置id为dataSource的数据源Bean和id为jdbcTemplate的JDBC模板Bean,并将数据源注入到JDBC模板中,如文件所示。

<?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-4.3.xsd">
<!-- 1配置数据源 -->
<bean id="dataSource" class=
"org.springframework.jdbc.datasource.DriverManagerDataSource">
<!--数据库驱动 -->
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<!--连接数据库的url -->
<property name="url" value="jdbc:mysql://localhost:3306/spring?useSSL=false" />
<!--连接数据库的用户名 -->
<property name="username" value="root" />
<!--连接数据库的密码 -->
<property name="password" value="123456" />
</bean>
<!-- 2配置JDBC模板 -->
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 默认必须使用数据源 -->
<property name="dataSource" ref="dataSource" />
</bean> </beans>

(4)在chapter04模块的src/main/java目录下,创建一个com.awen.jdbc包,在该包中创建测试类JdbcTemplateTest。在该类的main()方法中通过Spring容器获取在配置文件中定义的JdbcTemplate实例,然后使用该实例的execute(String sql)方法执行创建数据表的SQL语句,如文件所示。JdbcTemplateTest.java

package com.awen.jdbc;
import java.util.List; import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
public class JdbcTemplateTest {
/**
* 使用execute()方法建表
*/
public static void main(String[] args) {
// 加载配置文件
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
// 获取JdbcTemplate实例
JdbcTemplate jdTemplate =
(JdbcTemplate) applicationContext.getBean("jdbcTemplate");
// 使用execute()方法执行SQL语句,创建用户账户管理表account
jdTemplate.execute("create table account(" +
"id int primary key auto_increment," +
"username varchar(50)," +
"balance double)");
System.out.println("账户表account创建成功!");
} }

成功运行程序后,

D:\Environments\jdk-11.0.2\bin\java.exe -javaagent:D:\Java\ideaIU-2019.2.win\lib\idea_rt.jar=9076:D:\Java\ideaIU-2019.2.win\bin -Dfile.encoding=UTF-8 -classpath D:\IdeaProjects\JavaEE-enterprise-application-development-tutorial\chapter04\target\classes;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-webmvc\5.2.3.RELEASE\spring-webmvc-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-aop\5.2.3.RELEASE\spring-aop-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-beans\5.2.3.RELEASE\spring-beans-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-core\5.2.3.RELEASE\spring-core-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-jcl\5.2.3.RELEASE\spring-jcl-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-expression\5.2.3.RELEASE\spring-expression-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-web\5.2.3.RELEASE\spring-web-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-context\5.2.3.RELEASE\spring-context-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-jdbc\5.2.3.RELEASE\spring-jdbc-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-tx\5.2.3.RELEASE\spring-tx-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\commons-logging\commons-logging\1.2\commons-logging-1.2.jar;D:\Environments\apache-maven-3.6.2\maven-repo\junit\junit\4.12\junit-4.12.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;D:\Environments\apache-maven-3.6.2\maven-repo\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar com.awen.jdbc.JdbcTemplateTest
账户表account创建成功! Process finished with exit code 0

再次查询spring数据库,其结果如图所示。

从图可以看出,程序使用execute(String sql)方法执行的SQL语句已成功创建了数据表account。

删除MySQL数据表的通用语法:

DROP TABLE table_name ;

再删除掉DROP TABLE account;

问题:

我安装MySQL 版本5.7.28

Connector/J version

 <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
** BEGIN NESTED EXCEPTION ** 

javax.net.ssl.SSLException
MESSAGE: closing inbound before receiving peer's close_notify STACKTRACE: javax.net.ssl.SSLException: closing inbound before receiving peer's close_notify
at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:129)
at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:117)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:308)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:264)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:255)
at java.base/sun.security.ssl.SSLSocketImpl.shutdownInput(SSLSocketImpl.java:645)
at java.base/sun.security.ssl.SSLSocketImpl.shutdownInput(SSLSocketImpl.java:624)
at com.mysql.jdbc.MysqlIO.quit(MysqlIO.java:2249)
at com.mysql.jdbc.ConnectionImpl.realClose(ConnectionImpl.java:4232)
at com.mysql.jdbc.ConnectionImpl.close(ConnectionImpl.java:1472)
at org.springframework.jdbc.datasource.DataSourceUtils.doCloseConnection(DataSourceUtils.java:402)
at org.springframework.jdbc.datasource.DataSourceUtils.doReleaseConnection(DataSourceUtils.java:389)
at org.springframework.jdbc.datasource.DataSourceUtils.releaseConnection(DataSourceUtils.java:356)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:392)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:418)
at com.awen.jdbc.JdbcTemplateTest.main(JdbcTemplateTest.java:20) ** END NESTED EXCEPTION ** 账户表account创建成功! Process finished with exit code 0

javax.net.ssl.SSLException

MESSAGE: closing inbound before receiving peer’s close_notify

<!--连接数据库的url -->
<property name="url" value="jdbc:mysql://localhost:3306/spring?useSSL=false" />

配置url加上 useSSL=false 解决

使用JUnit单元测试

​ 在软件开发过程中,需要有相应的测试工作。依据测试目的不同,可以将软件测试分为单元测试、集成测试、确认测试和系统测试等。其中单元测试在软件开发阶段是最底层的测试,它易于及时发现并解决问题。JUnit就是一个进行单元测试的开源框架,下面以上个示例,来学习单元测试框架JUnit4的使用。

将文件JdbcTemplateTest.java中的main()方法,修改成名称为mainTest()的普通方法,并在方法上添加单元测试的注解@Test,其代码如下所示。

@Test
public void mainTest() {
// 加载配置文件
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
// 获取JdbcTemplate实例
JdbcTemplate jdTemplate =
(JdbcTemplate) applicationContext.getBean("jdbcTemplate");
// 使用execute()方法执行SQL语句,创建用户账户管理表account
jdTemplate.execute("create table account(" +
"id int primary key auto_increment," +
"username varchar(50)," +
"balance double)");
System.out.println("账户表account创建成功!");
}

@Test就是Junit4用于测试的注解,要测试哪个方法,只需要在相应测试的方法上添加此注解即可。

当在需要测试的方法上添加@Test注解后,idea会在所添加的@Test处报出Test cannot be resolved to a type的错误。

 <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>

pom.xml加入依赖后,在测试类中会自动导入org.junit.Test包,此时测试类中的代码将不再报错。在执行程序时,只需使用鼠标右键,在弹出的快捷菜单中选择Run mainTest()选项来运行测试方法即可,

单击JUnit Test选项后,Unit视图窗口的进度条为绿色表明运行结果正确,如果进度条为红色则表示有错误,并且会在窗口中显示所报的错误信息。需要注意的是,在运行此方法时,需要先将数据库中已创建好的account表删除,否则执行此方法时会报出account表已经存在的错误。测试执行通过后,Console控制台的输出结果如图所示。

运行结果可以看出,mainTest()方法已经执行成功,这就是单元测试的使用。

update()

update()

update()用于执行插入、更新和删除操作

update()方法可以完成插入、更新和删除数据的操作。在JdbcTemplate类中,提供了一系列的update()方法,其常用方法如表所示。

int update(String sql) 该方法是最简单的update方法重载形式,它直接执行传入的SQL语句,并返回受影响的行数。

接下来,通过一个用户账户管理的案例来演示update()方法的使用。

小案例

在chapter04项目的com.itheima.jdbc包中,创建Account类,在该类中定义id、username和balance属性,以及其对应的getter/setter方法,如文件所示。

Account.java

package com.awen.jdbc;
public class Account {
private Integer id; // 账户id
private String username; // 用户名
private Double balance; // 账户余额
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Double getBalance() {
return balance;
}
public void setBalance(Double balance) {
this.balance = balance;
}
public String toString() {
return "Account [id=" + id + ", "
+ "username=" + username +
", balance=" + balance + "]";
}
}

(2)在com.awen.jdbc包中,创建接口AccountDao,并在接口中定义添加、更新和删除账户的方法,如文件所示。AccountDao.java

package com.awen.jdbc;

import java.util.List;

public interface AccountDao {
// 添加
public int addAccount(Account account);
// 更新
public int updateAccount(Account account);
// 删除
public int deleteAccount(int id); // 通过id查询
public Account findAccountById(int id);
// 查询所有账户
public List<Account> findAllAccount();
}

(3)在com.awen.jdbc包中,创建AccountDao接口的实现类AccountDaoImpl,并在类中实现添加、更新和删除账户的方法,编辑后如文件所示。

AccountDaoImpl.java

package com.awen.jdbc;
import java.util.List; import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public class AccountDaoImpl implements AccountDao {
// 声明JdbcTemplate属性及其setter方法
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
// 添加账户
public int addAccount(Account account) {
// 定义SQL
String sql = "insert into account(username,balance) value(?,?)";
// 定义数组来存放SQL语句中的参数
Object[] obj = new Object[] {
account.getUsername(),
account.getBalance()
};
// 执行添加操作,返回的是受SQL语句影响的记录条数
int num = this.jdbcTemplate.update(sql, obj);
return num;
}
// 更新账户
public int updateAccount(Account account) {
// 定义SQL
String sql = "update account set username=?,balance=? where id = ?";
// 定义数组来存放SQL语句中的参数
Object[] params = new Object[] {
account.getUsername(),
account.getBalance(),
account.getId()
};
// 执行添加操作,返回的是受SQL语句影响的记录条数
int num = this.jdbcTemplate.update(sql, params);
return num;
}
// 删除账户
public int deleteAccount(int id) {
// 定义SQL
String sql = "delete from account where id = ? ";
// 执行添加操作,返回的是受SQL语句影响的记录条数
int num = this.jdbcTemplate.update(sql, id);
return num;
} }

从上述三种操作的代码可以看出,添加、更新和删除操作的实现步骤类似,只是定义的SQL语句有所不同。

SQL语句不同 添加 更新 删除

insert into account(username,balance) value(?,?)
update account set username=?,balance=? where id = ?
delete from account where id = ?

(4)在applicationContext.xml中,定义一个id为accountDao的Bean,该Bean用于将jdbcTemplate注入到accountDao实例中,其代码如下所示。

<!--定义id为accountDao的Bean-->
<bean id="accountDao" class="com.awen.jdbc.AccountDaoImpl">
<!-- 将jdbcTemplate注入到accountDao实例中 -->
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>

(5)在测试类JdbcTemplateTest中,添加一个测试方法addAccountTest(),该方法主要用于添加用户账户信息,其代码如下所示。

@Test
public void addAccountTest() {
// 加载配置文件
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
// 获取AccountDao实例
AccountDao accountDao =
(AccountDao) applicationContext.getBean("accountDao");
// 创建Account对象,并向Account对象中添加数据
Account account = new Account();
account.setUsername("tom");
account.setBalance(1000.00);
// 执行addAccount()方法,并获取返回结果
int num = accountDao.addAccount(account);
if (num > 0) {
System.out.println("成功插入了" + num + "条数据!");
} else {
System.out.println("插入操作执行失败!");
}
}

在上述代码中,获取了AccountDao的实例后,又创建了Account对象,并向Account对象中添加了属性值。然后调用了AccountDao对象的addAccount()方法向数据表中添加一条数据。最后,通过返回的受影响的行数来判断数据是否插入成功。使用Junit4测试运行后,控制台的输出结果如下所示。

D:\Environments\jdk-11.0.2\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 -javaagent:D:\Java\ideaIU-2019.2.win\lib\idea_rt.jar=10289:D:\Java\ideaIU-2019.2.win\bin -Dfile.encoding=UTF-8 -classpath D:\Java\ideaIU-2019.2.win\lib\idea_rt.jar;D:\Java\ideaIU-2019.2.win\plugins\junit\lib\junit5-rt.jar;D:\Java\ideaIU-2019.2.win\plugins\junit\lib\junit-rt.jar;D:\IdeaProjects\JavaEE-enterprise-application-development-tutorial\chapter04\target\classes;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-webmvc\5.2.3.RELEASE\spring-webmvc-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-aop\5.2.3.RELEASE\spring-aop-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-beans\5.2.3.RELEASE\spring-beans-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-core\5.2.3.RELEASE\spring-core-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-jcl\5.2.3.RELEASE\spring-jcl-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-expression\5.2.3.RELEASE\spring-expression-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-web\5.2.3.RELEASE\spring-web-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-context\5.2.3.RELEASE\spring-context-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-jdbc\5.2.3.RELEASE\spring-jdbc-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-tx\5.2.3.RELEASE\spring-tx-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\commons-logging\commons-logging\1.2\commons-logging-1.2.jar;D:\Environments\apache-maven-3.6.2\maven-repo\junit\junit\4.12\junit-4.12.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;D:\Environments\apache-maven-3.6.2\maven-repo\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 com.awen.jdbc.JdbcTemplateTest,addAccountTest
成功插入了1条数据! Process finished with exit code 0

此时再次查询数据库中的account表,其结果如图所示。

account表从图可以看出,使用JdbcTemplate的update()方法已成功地向数据表中插入了一条数据。

(6)执行完插入操作后,接下来使用JdbcTemplate类的update()方法执行更新操作。在测试类JdbcTemplateTest中,添加一个测试方法updateAccountTest(),其代码如下所示。

@Test
public void updateAccountTest() {
// 加载配置文件
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
// 获取AccountDao实例
AccountDao accountDao =
(AccountDao) applicationContext.getBean("accountDao");
// 创建Account对象,并向Account对象中添加数据
Account account = new Account();
account.setId(1);
account.setUsername("tom");
account.setBalance(2000.00);
// 执行updateAccount()方法,并获取返回结果
int num = accountDao.updateAccount(account);
if (num > 0) {
System.out.println("成功修改了" + num + "条数据!");
} else {
System.out.println("修改操作执行失败!");
}
}

与addAccountTest()方法相比,更新操作的代码增加了id属性值的设置,并将余额修改为2000后,调用了AccountDao对象中的updateAccount()方法执行对数据表的更新操作。

D:\Environments\jdk-11.0.2\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 -javaagent:D:\Java\ideaIU-2019.2.win\lib\idea_rt.jar=10374:D:\Java\ideaIU-2019.2.win\bin -Dfile.encoding=UTF-8 -classpath D:\Java\ideaIU-2019.2.win\lib\idea_rt.jar;D:\Java\ideaIU-2019.2.win\plugins\junit\lib\junit5-rt.jar;D:\Java\ideaIU-2019.2.win\plugins\junit\lib\junit-rt.jar;D:\IdeaProjects\JavaEE-enterprise-application-development-tutorial\chapter04\target\classes;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-webmvc\5.2.3.RELEASE\spring-webmvc-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-aop\5.2.3.RELEASE\spring-aop-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-beans\5.2.3.RELEASE\spring-beans-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-core\5.2.3.RELEASE\spring-core-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-jcl\5.2.3.RELEASE\spring-jcl-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-expression\5.2.3.RELEASE\spring-expression-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-web\5.2.3.RELEASE\spring-web-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-context\5.2.3.RELEASE\spring-context-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-jdbc\5.2.3.RELEASE\spring-jdbc-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-tx\5.2.3.RELEASE\spring-tx-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\commons-logging\commons-logging\1.2\commons-logging-1.2.jar;D:\Environments\apache-maven-3.6.2\maven-repo\junit\junit\4.12\junit-4.12.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;D:\Environments\apache-maven-3.6.2\maven-repo\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 com.awen.jdbc.JdbcTemplateTest,updateAccountTest
成功修改了1条数据! Process finished with exit code 0

使用Junit4运行方法后,再次查询数据库中的account表,其结果如图所示。

图 account表从图可以看出,使用update()方法已成功更新了account表中id为1的账户余额信息。

(7)在测试类JdbcTemplateTest中,添加一个测试方法deleteAccountTest(),来执行删除操作,其代码如下所示。

@Test
public void deleteAccountTest() {
// 加载配置文件
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
// 获取AccountDao实例
AccountDao accountDao =
(AccountDao) applicationContext.getBean("accountDao");
// 执行deleteAccount()方法,并获取返回结果
int num = accountDao.deleteAccount(1);
if (num > 0) {
System.out.println("成功删除了" + num + "条数据!");
} else {
System.out.println("删除操作执行失败!");
}
}

在上述代码中,获取了AccountDao的实例后,执行了实例中的deleteAccount()方法来删除id为1的数据。

使用Junit4测试运行方法后,

D:\Environments\jdk-11.0.2\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 -javaagent:D:\Java\ideaIU-2019.2.win\lib\idea_rt.jar=10410:D:\Java\ideaIU-2019.2.win\bin -Dfile.encoding=UTF-8 -classpath D:\Java\ideaIU-2019.2.win\lib\idea_rt.jar;D:\Java\ideaIU-2019.2.win\plugins\junit\lib\junit5-rt.jar;D:\Java\ideaIU-2019.2.win\plugins\junit\lib\junit-rt.jar;D:\IdeaProjects\JavaEE-enterprise-application-development-tutorial\chapter04\target\classes;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-webmvc\5.2.3.RELEASE\spring-webmvc-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-aop\5.2.3.RELEASE\spring-aop-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-beans\5.2.3.RELEASE\spring-beans-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-core\5.2.3.RELEASE\spring-core-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-jcl\5.2.3.RELEASE\spring-jcl-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-expression\5.2.3.RELEASE\spring-expression-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-web\5.2.3.RELEASE\spring-web-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-context\5.2.3.RELEASE\spring-context-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-jdbc\5.2.3.RELEASE\spring-jdbc-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-tx\5.2.3.RELEASE\spring-tx-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\commons-logging\commons-logging\1.2\commons-logging-1.2.jar;D:\Environments\apache-maven-3.6.2\maven-repo\junit\junit\4.12\junit-4.12.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;D:\Environments\apache-maven-3.6.2\maven-repo\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 com.awen.jdbc.JdbcTemplateTest,deleteAccountTest
成功删除了1条数据! Process finished with exit code 0

查询account表中数据,其结果如图所示。

account表从图可以看出,已成功通过delete()方法删除了id为1的数据。由于account表中只有一条数据,所以删除后表中数据为空。

query()

query()

query()用于执行数据查询操作

​ JdbcTemplate类中还提供了大量的query()方法来处理各种对数据库表的查询操作。其中,常用的几个query()方法如下表所示:

JdbcTemplate中常用的query()方法

了解了几个常用的query()方法后,接下来通过一个具体的案例来演示query()方法的使用,其实现步骤如下。

(1)向数据表account中插入几条数据可以利用上面添加也可以写SQL语句直接在MySQL里面执行(也可以使用数据库图形化工具手动向表中插入数据),插入后account表中的数据如图所示。

​ 本章对Spring框架中,使用JDBC进行数据操作的知识进行了详细讲解。首先讲解了Spring JDBC中的核心类以及如何在Spring中配置JDBC,然后通过案例讲解了Spring JDBC核心类JdbcTemplate中常用方法的使用。

(2)在AccountDao中,分别创建一个通过id查询单个账户和查询所有账户的方法,其代码如下所示。

// 通过id查询
public Account findAccountById(int id);
// 查询所有账户
public List<Account> findAllAccount();

(3)在AccountDao接口的实现类AccountDaoImpl中,实现接口中的方法,并使用query()方法分别进行查询,其代码如下所示。

// 通过id查询账户数据信息
public Account findAccountById(int id) {
//定义SQL语句
String sql = "select * from account where id = ?";
// 创建一个新的BeanPropertyRowMapper对象
RowMapper<Account> rowMapper =
new BeanPropertyRowMapper<Account>(Account.class);
// 将id绑定到SQL语句中,并通过RowMapper返回一个Object类型的单行记录
return this.jdbcTemplate.queryForObject(sql, rowMapper, id);
}
// 查询所有账户信息
public List<Account> findAllAccount() {
// 定义SQL语句
String sql = "select * from account";
// 创建一个新的BeanPropertyRowMapper对象
RowMapper<Account> rowMapper =
new BeanPropertyRowMapper<Account>(Account.class);
// 执行静态的SQL查询,并通过RowMapper返回结果
return this.jdbcTemplate.query(sql, rowMapper);
}

在上面两个方法代码中,BeanPropertyRowMapper是RowMapper接口的实现类,它可以自动地将数据表中的数据映射到用户自定义的类中(前提是用户自定义类中的字段要与数据表中的字段相对应)。创建完BeanPropertyRowMapper对象后,在findAccountById()方法中通过queryForObject()方法返回了一个Object类型的单行记录,而在findAllAccount()方法中通过query()方法返回了一个结果集合。

(4)在测试类JdbcTemplateTest中,添加一个测试方法findAccountByIdTest()来测试条件查询,其代码如下所示。

@Test
public void findAccountByIdTest() {
// 加载配置文件
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
// 获取AccountDao实例
AccountDao accountDao =
(AccountDao) applicationContext.getBean("accountDao");
// 执行findAccountById()方法
Account account = accountDao.findAccountById(2);
System.out.println(account);
}

上述代码通过执行findAccountById()方法获取了id为2的对象信息,并通过输出语句输出。使用JUnit4测试运行后,控制台的输出结果。 运行结果

D:\Environments\jdk-11.0.2\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 -javaagent:D:\Java\ideaIU-2019.2.win\lib\idea_rt.jar=10600:D:\Java\ideaIU-2019.2.win\bin -Dfile.encoding=UTF-8 -classpath D:\Java\ideaIU-2019.2.win\lib\idea_rt.jar;D:\Java\ideaIU-2019.2.win\plugins\junit\lib\junit5-rt.jar;D:\Java\ideaIU-2019.2.win\plugins\junit\lib\junit-rt.jar;D:\IdeaProjects\JavaEE-enterprise-application-development-tutorial\chapter04\target\classes;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-webmvc\5.2.3.RELEASE\spring-webmvc-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-aop\5.2.3.RELEASE\spring-aop-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-beans\5.2.3.RELEASE\spring-beans-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-core\5.2.3.RELEASE\spring-core-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-jcl\5.2.3.RELEASE\spring-jcl-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-expression\5.2.3.RELEASE\spring-expression-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-web\5.2.3.RELEASE\spring-web-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-context\5.2.3.RELEASE\spring-context-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-jdbc\5.2.3.RELEASE\spring-jdbc-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-tx\5.2.3.RELEASE\spring-tx-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\commons-logging\commons-logging\1.2\commons-logging-1.2.jar;D:\Environments\apache-maven-3.6.2\maven-repo\junit\junit\4.12\junit-4.12.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;D:\Environments\apache-maven-3.6.2\maven-repo\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 com.awen.jdbc.JdbcTemplateTest,findAccountByIdTest
Account [id=2, username=柳小子, balance=10000.0] Process finished with exit code 0

com.awen.jdbc.JdbcTemplateTest,findAccountByIdTest

Account [id=2, username=柳小子, balance=10000.0]

5)测试完条件查询单个数据的方法后,接下来测试查询所有用户账户信息的方法。在测试类JdbcTemplateTest中,添加一个测试方法findAllAccountTest(),其代码如下所示。

@Test
public void findAllAccountTest() {
// 加载配置文件
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
// 获取AccountDao实例
AccountDao accountDao =
(AccountDao) applicationContext.getBean("accountDao");
// 执行findAllAccount()方法,获取Account对象的集合
List<Account> account = accountDao.findAllAccount();
// 循环输出集合中的对象
for (Account act : account) {
System.out.println(act);
}
}

在上述代码中,调用了AccountDao对象的findAllAccount()方法查询所有用户账户信息集合,并通过for循环输出查询结果。使用JUnit4成功运行findAllUserTest()方法后,控制台的显示信息如下所示。

D:\Environments\jdk-11.0.2\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 -javaagent:D:\Java\ideaIU-2019.2.win\lib\idea_rt.jar=10628:D:\Java\ideaIU-2019.2.win\bin -Dfile.encoding=UTF-8 -classpath D:\Java\ideaIU-2019.2.win\lib\idea_rt.jar;D:\Java\ideaIU-2019.2.win\plugins\junit\lib\junit5-rt.jar;D:\Java\ideaIU-2019.2.win\plugins\junit\lib\junit-rt.jar;D:\IdeaProjects\JavaEE-enterprise-application-development-tutorial\chapter04\target\classes;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-webmvc\5.2.3.RELEASE\spring-webmvc-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-aop\5.2.3.RELEASE\spring-aop-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-beans\5.2.3.RELEASE\spring-beans-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-core\5.2.3.RELEASE\spring-core-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-jcl\5.2.3.RELEASE\spring-jcl-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-expression\5.2.3.RELEASE\spring-expression-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-web\5.2.3.RELEASE\spring-web-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-context\5.2.3.RELEASE\spring-context-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-jdbc\5.2.3.RELEASE\spring-jdbc-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\springframework\spring-tx\5.2.3.RELEASE\spring-tx-5.2.3.RELEASE.jar;D:\Environments\apache-maven-3.6.2\maven-repo\commons-logging\commons-logging\1.2\commons-logging-1.2.jar;D:\Environments\apache-maven-3.6.2\maven-repo\junit\junit\4.12\junit-4.12.jar;D:\Environments\apache-maven-3.6.2\maven-repo\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;D:\Environments\apache-maven-3.6.2\maven-repo\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 com.awen.jdbc.JdbcTemplateTest,findAllAccountTest
Account [id=2, username=柳小子, balance=10000.0]
Account [id=3, username=小柳子, balance=10.0]
Account [id=4, username=柳铁蛋, balance=20.0]
Account [id=5, username=柳狗柱, balance=20.0] Process finished with exit code 0

从运行结果从可以看出,数据表account中的4条记录都已经被查询出来。

学会如何使用Spring框架进行数据库开发,深切的体会到Spring框架的强大。

【Spring】Spring的数据库开发 - 2、Spring JdbcTemplate的常用方法(execute、update、query)的更多相关文章

  1. Eclipse 下Spring cloud项目集成开发插件Spring Tool Suite (STS) 安装

    安装eclipse插件 Help->Eclipse Marketplace-> Search中查找"Spring Tool Suite (STS) for Eclipse&quo ...

  2. Spring的数据库开发

                                Spring JDBC框架操作mysql数据库 Spring中的JDBC为我们省去连接和关闭数据库的代码,我们着重关注对数据库的操作.Sprin ...

  3. 图书-技术-SpringBoot:《Spring Boot 企业级应用开发实战》

    ylbtech-图书-技术-SpringBoot:<Spring Boot 企业级应用开发实战> Spring Boot 企业级应用开发实战,全书围绕如何整合以 Spring Boot 为 ...

  4. [web开发] Vue + spring boot + echart 微博爬虫展示平台

    1.微博登录 2.爬取数据 3.mysql存储 4.pyechart本地展示 5.用vue搭建网站web展示 先放图: 1.微博登录 新浪微博的登录不是简单的post就能解决的,他的登录有加密,所以我 ...

  5. 手写Mybatis和Spring整合简单版示例窥探Spring的强大扩展能力

    Spring 扩展点 **本人博客网站 **IT小神 www.itxiaoshen.com 官网地址****:https://spring.io/projects/spring-framework T ...

  6. 【Spring】Spring的数据库开发 - 1、Spring JDBC的配置和Spring JdbcTemplate的解析

    Spring JDBC 文章目录 Spring JDBC Spring JdbcTemplate的解析 Spring JDBC的配置 简单记录-Java EE企业级应用开发教程(Spring+Spri ...

  7. Spring数据库开发

    Spring的数据库开发 #Spring中JDBC模板的作用 JDBC模板负责数据库资源管理和错误处理: #熟悉Spring  JDBC的配置 配置数据源和jdbc模板 <?xml versio ...

  8. Spring - 数据库开发概述

      Spring 数据库开发 Spring 的 JDBC 模块负责数据库资源管理和镨误处理,大大简化了开发人员对数据库的操作,使得开发人员可以从繁琐的数据库操作中解脱出来,从而将更多的精力投入到编写业 ...

  9. Spring框架针对dao层的jdbcTemplate操作crud之update修改数据库操作

    使用jdbcTemplate 原理是把加载驱动Class.forName("com.mysql.jdbc.Driver"); 和连接数据库Connection conn=Drive ...

随机推荐

  1. C++ 虚函数表与多态 —— 多态的简单用法

    首先看下边的代码,先创建一个父类,然后在来一个继承父类的子类,两个类中都有自己的 play() 方法,在代码的第35-37行,创建一个父类指针,然后将子类地址引用赋值给父类,这时调用 P 指针的 pl ...

  2. oracle修改数据文件目录

    一.停库修改数据文件目录.文件名 1.当前数据文件目录 SQL> select file_name from dba_data_files; FILE_NAME ---------------- ...

  3. 字节跳动内部微服务架构-Docker实战学习笔记分享 真香

    前言 基于 Spring Cloud 的微服务设计和开发,已经越来越多地得到了更多企业的推广和应用,而 Spring Cloud 社区也在不断的迅速发展壮大之中,近几年时间,Spring Cloud ...

  4. db2常用操作

    1. db2建立远程节点编目及删除 db2 catalog tcpip node nodeName remote remoteIp server remotePort db2 list node di ...

  5. Oracle数据导入Mysql中

    一.Navicat Premium中的数据迁移工具 为了生产库释放部分资源,需要将API模块迁移到mysql中,及需要导数据. 尝试了oracle to mysql工具,迁移时报错不说,这么大的数据量 ...

  6. Django使用channels实现Websocket连接

    简述: 需求:消息实时推送消息以及通知功能,采用django-channels来实现websocket进行实时通讯.并使用docker.daphne启动通道,保持websocket后台运行 介绍Dja ...

  7. react第十七单元(redux和组件之间的通信,react-redux的相关api的用法)

    第十七单元(redux和组件之间的通信,react-redux的相关api的用法) #课程目标 什么是redux-redux react-redux的作用是什么 react-redux如何应用 #知识 ...

  8. jmeter性能测试-高并发分布式部署

    jmeter什么要做分布式部署? jmeter是运行在JVM虚拟机上的,当模拟大量并发时,对运行机器的性能/网络负载会很大. 此时就需要使用jmeter的分布式部署功能,实现多台被控机器同时并发访问被 ...

  9. CSRF学习

    前提环境:网站存在CSRF漏洞(也就是过于相信访问请求,只判断了用户是否存在cookie,并未判断请求的发起者) CSRF攻击原理,用户A需要转账,用户A正常向银行网站发送请求登录,登录成功后银行网站 ...

  10. 【原创】Linux PCI驱动框架分析(一)

    背景 Read the fucking source code! --By 鲁迅 A picture is worth a thousand words. --By 高尔基 说明: Kernel版本: ...