Spring JDBC
Spring JDBC模块分四个包:core(核心包) 、dataSource(数据源包)、object(对象包)和support(支持包)
图片来源于www.itheima.com
JdbcTemplate
JdbcTemplate是Spring JDBC的核心类,针对数据库的操作,Spring框架提供了JdbcTemplate类,该类是Spring框架数据抽象层的基础。
常用方法:
图片来源于www.itheima.com
execute()方法测试:
创建数据库,这里我用到的数据库是mysql,相应的数据库驱动以及jar包如下图所示:
然后创建applicationContext.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-4.3.xsd">
<!-- 1.配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 数据库驱动 -->
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<!-- 连接数据库的url-->
<property name="url" value="jdbc:mysql://localhost:3306/spring"></property>
<!-- 连接数据库的用户名-->
<property name="username" value="root"></property>
<!-- 连接数据库的密码-->
<property name="password" value="123456"></property>
</bean>
<!-- 2.配置JDBC模板 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 默认必须使用数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
在数据库中创建一张表,我使用的工具是Navicat
编写测试类JdbcTemplateTest:
package cn.edu.jdbc;
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 jdbcTemplateTest=(JdbcTemplate) applicationContext.getBean("jdbcTemplate");
//使用excute方法执行sql语句,创建用户账户管理表account
jdbcTemplateTest.execute("create table account("+
"id int primary key auto_increment,"+
"username varchar(50),"+
"balance double)");
System.out.println("账户表accunt创建成功");
}
}
运行结果和数据库变更后的结果如下
updata()测试,插入删除更新
新建Account类,类中有表中的属性值
package cn.edu.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;
}
@Override
public String toString() {
return "Account [id=" + id + ", username=" + username + ", balance=" + balance + "]";
}
}
新建AccountDao接口
package cn.edu.jdbc;
public interface AccountDao {
//添加
public int addAccount(Account account);
//更新
public int updataAccount(Account account);
//删除
public int deleteAccount(int id);
}
新建AccountDaoImpl类实现Account中的方法
package cn.edu.jdbc;
import org.springframework.jdbc.core.JdbcTemplate;
public class AccountDaoImpl implements AccountDao {
// 声明JdbcTemplate属性及其setter
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
// 添加账户
@Override
public int addAccount(Account account) {
// 定义sql
String sql = "insert into account(username,balance) value(?,?)";
// 定义数组来存放sql语句中的参数
Object[] obj = new Object[] { account.getUsername(), account.getBalance() };
//执行添加操作后返回的受影响的行数
int num = this.jdbcTemplate.update(sql, obj);
return num;
}
// 更新账户
@Override
public int updataAccount(Account account) {
String sql = "update account set username=? , balance=? where id=?";
// 定义数组来存放sql语句中的参数
Object[] params = new Object[] {account.getUsername(), account.getBalance(), account.getId() };
//执行更新操作后返回的受影响的行数
int num = this.jdbcTemplate.update(sql, params);
return num;
}
// 删除账户
@Override
public int deleteAccount(int id) {
String sql = "delete from account where id=?";
//执行删除操作后返回的受影响的行数
int num = this.jdbcTemplate.update(sql, id);
return num;
}
}
配置applicationContext.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-4.3.xsd">
<!-- 1.配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 数据库驱动 -->
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<!-- 连接数据库的url-->
<property name="url" value="jdbc:mysql://localhost:3306/spring"></property>
<!-- 连接数据库的用户名-->
<property name="username" value="root"></property>
<!-- 连接数据库的密码-->
<property name="password" value="123456"></property>
</bean>
<!-- 2.配置JDBC模板 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 默认必须使用数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 定义id为accountDao的Bean -->
<bean id="accountDao" class="cn.edu.jdbc.AccountDaoImpl">
<!-- 将jdbcTemplate注入到accountDao实例中 -->
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
新建测试类JdbcTemplateTest
package cn.edu.jdbc;
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 jdbcTemplateTest=(JdbcTemplate) applicationContext.getBean("jdbcTemplate");
//使用excute方法执行sql语句,创建用户账户管理表account
jdbcTemplateTest.execute("create table account("+
"id int primary key auto_increment,"+
"username varchar(50),"+
"balance double)");
System.out.println("账户表accunt创建成功");
}
/**
*
* 学习junit4测试
*
*/
@Test
public void mainTest() {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
//获取JdbcTemplate实例
JdbcTemplate jdbcTemplateTest=(JdbcTemplate) applicationContext.getBean("jdbcTemplate");
//使用excute方法执行sql语句,创建用户账户管理表account
jdbcTemplateTest.execute("create table account("+
"id int primary key auto_increment,"+
"username varchar(50),"+
"balance double)");
System.out.println("账户表accunt创建成功");
}
@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("user");
account.setBalance(1000.00);
//执行addAccount方法并获取返回结果
int num = accountDao.addAccount(account);
if(num>0)
System.out.println("成功插入了"+num+"条数据");
else
System.out.println("插入失败");
}
@Test
public void updataAccountTest(){
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
//获取accountDao实例
AccountDao accountDao=(AccountDao) applicationContext.getBean("accountDao");
//创建Account对象并向Account对象中添加数据
Account account=new Account();
account.setId(1);
account.setUsername("user01");
account.setBalance(2000.00);
//执行
int num =accountDao.updataAccount(account);
if(num>0)
System.out.println("成功更新了"+num+"条数据");
else
System.out.println("更新失败");
}
@Test
public void deleteAccountTest(){
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
//获取accountDao实例
AccountDao accountDao=(AccountDao) applicationContext.getBean("accountDao");
Account account=new Account();
account.setId(3);
int num =accountDao.deleteAccount(account.getId());
if(num>0)
System.out.println("成功删除了"+num+"条数据");
else
System.out.println("删除失败");
}
}
使用junit4进行单元测试,插入删除更新操作均成功。
query()进行查询
图片来源于www.itheima.com
在表中随意添加几条记录,然后在AccountDaoImpl实现类中加入如下代码,需要注意的是单条记录查询是返回的是一个Account对象,我的Account类中的属性与数据库的关键字段是对应的,而全部查询时返回的是一个Account类型的List数组,使用foreach遍历即可。参数中使用的RowMapper需要按照代码所示的固定格式写,目的是为了返回Account类型的对象或者数组,不要过于复杂化的去理解它。
//通过id查询账户数据
@Override
public Account findAccountById(int id) {
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);
}
//查询所有账户信息
@Override
public List<Account> findAllAccount() {
String sql="select * from account";
RowMapper<Account> rowMapper=new BeanPropertyRowMapper<Account>(Account.class);
//执行查询
return this.jdbcTemplate.query(sql, rowMapper);
}
测试类JdbcTemplateTest中添加如下代码进行单元测试:
@Test
public void findAccountByIdTest(){
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
//获取accountDao实例
AccountDao accountDao=(AccountDao) applicationContext.getBean("accountDao");
Account account = accountDao.findAccountById(4);
System.out.println(account);
//System.out.println("id="+account.getId()+",username="+account.getUsername()+",balance="+account.getBalance());
}
@Test
public void findAllAccountTest(){
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
//获取accountDao实例
AccountDao accountDao=(AccountDao) applicationContext.getBean("accountDao");
List<Account> accountList=accountDao.findAllAccount();
//循环输出集合中的对象
for (Account account : accountList) {
System.out.println(account);
}
}
以上代码进行单元测试时均可以正确运行,多调试,才能在错误中学到东西。
本博客仅供个人学习,请勿用于商业用途。