首页 技术 正文
技术 2022年11月9日
0 收藏 484 点赞 2,365 浏览 9109 个字

Spring的数据库开发

1、Spring JDBC

1)、Spring JDBC模块的作用:Spring的JDBC模块负责数据库资源管理和错误处理,大大简化了开发人员对数据库的操作,使得开发人员可以从繁琐的数据库操作中解脱出来,从而将更多的精力投入到编写业务逻辑当中(只要由new实例就可以用IOC实现,只要有setter方法就可以用DI实现)

2)、Spring JdbcTemplate的解析:

a)、JdbcTemplate类是Spring JDBC的核心类

b)、JdbcTemplate类的继承结构具体如下图所示:

Java EE学习笔记(四)

c)、DataSource(连接池,也称数据源):其主要功能是获取数据库连接,还可以引入对数据库连接的缓冲池分布式事务的支持,它可以作为访问数据库资源的标准接口

d)、SQLExceptionTranslator:该接口负责对SQLException进行转译工作。通过必要的设置获取SQLExceptionTranslator中的方法,可以使JdbcTemplate在需要处理SQLException时,委托SQLExceptionTranslator的实现类来完成相关的转译工作

e)、JdbcOperations接口定义了在JdbcTemplate类中可以使用的操作集合,包括添加、修改、查询和删除等操作

3)、Spring JDBC的配置

a)、Spring JDBC模块主要由4个包组成,分别是core(核心包)、dataSource(数据源包)、object(对象包)和support(支持包)

Java EE学习笔记(四)

b)、从上表可以看出,Spring对数据库的操作都封装在了这几个包中,而想要使用Spring JDBC,就需要对其进行配置,配置模板如下:

 <!--1、配置数据源-->
<bean id="dataSourceID" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring"/>
<property name="username" value="root"/>
<property name="password" value="****"/>
</bean> <!--配置JDBC模板-->
<bean id="jdbcTemplateID" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSourceID"/> <!--注入数据源-->
</bean> <!--配置需要实例化的Bean-->
<bean id="xxx" class="Xxx">
<property name="jdbcTemplate" ref="jdbcTemplateID"/> <!--注入JDBC模板-->
</bean>

c)、关于上述示例dataSource配置中的4个属性说明,如下表所示:

Java EE学习笔记(四)

上表中的属性值在实际配置时,需要根据数据库类型设置进行相应配置

2、Spring JdbcTemplate的常用方法

1)、在JdbcTemplate核心类中,提供了大量的更新和查询数据库的方法:

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

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

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

Java EE学习笔记(四)

2)、execute()的使用:

a)、src->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="dataSourceID" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <!--1.1、数据库驱动 -->
<property name="driverClassName" value="com.mysql.jdbc.Driver" /> <!--1.2、连接数据库的url(即数据库所在地址) -->
<property name="url" value="jdbc:mysql://localhost:3306/spring" /> <!--1.3、连接数据库的用户名 -->
<property name="username" value="root" /> <!--1.4、连接数据库的密码 -->
<property name="password" value="******" />
</bean> <!-- 2、配置JDBC模板,并且注入数据源 -->
<bean id="jdbcTemplateID" class="org.springframework.jdbc.core.JdbcTemplate"> <!-- 2.1、默认必须使用数据源 -->
<property name="dataSource" ref="dataSourceID" />
</bean> <!--3、定义id为accountDaoID的Bean,即配置DAO层-->
<bean id="accountDaoID" class="com.itheima.jdbc.AccountDaoImpl"> <!-- 3.1、将jdbcTemplate注入到accountDao类实例中 -->
<property name="jdbcTemplate" ref="jdbcTemplateID" />
</bean> </beans>

b)、src->com.itheima.jdbc

①JdbcTemplateTest.java

 package com.itheima.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) { // 1、加载配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); // 2、获取JdbcTemplate实例
JdbcTemplate jdTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplateID"); // 3、使用该实例的execute()方法执行SQL语句,创建用户账户管理表account
jdTemplate.execute("create table account(" +
"id int primary key auto_increment," +
"username varchar(50)," +
"balance double)");
System.out.println("账户表account创建成功!");
}
}

②运行结果:

Java EE学习笔记(四)

Java EE学习笔记(四)

3)、update()的使用

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

Java EE学习笔记(四)

b)、src->com.itheima.jdbc

①普通账户类:Account.java

 package com.itheima.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 + "].";
}
}

②用户接口类:AccountDao.java

 package com.itheima.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();
}

③用户接口实现类:AccountDaoImpl.java

 package com.itheima.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 { // 数据访问层DAO // 1、声明JdbcTemplate属性及其setter方法
private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { // 由Spring容器注入JBDC模板来操作mysql
this.jdbcTemplate = jdbcTemplate;
} // 2、添加账户
public int addAccount(Account account) { // 2.1、定义SQL
String sql = "insert into account(username,balance) value(?,?)"; // 2.2、定义数组来存放SQL语句中的参数
Object[] obj = new Object[] { account.getUsername(), account.getBalance() }; // 2.3、执行添加操作,返回的是受SQL语句影响的记录条数
int num = this.jdbcTemplate.update(sql, obj);
return num;
} // 3、更新账户
public int updateAccount(Account account) { // 3.1、定义SQL
String sql = "update account set username=?,balance=? where id = ?"; // 3.2、定义数组来存放SQL语句中的参数
Object[] params = new Object[] { account.getUsername(), account.getBalance(), account.getId() }; /*
* 3.3、执行添加操作,返回的是受SQL语句影响的记录条数
* 第1个参数:sql操作语句
* 第2个参数:
*/
int num = this.jdbcTemplate.update(sql, params);
return num;
} // 4、删除账户
public int deleteAccount(int id) { // 4.1、定义SQL
String sql = "delete from account where id = ? "; // 4.2、执行添加操作,返回的是受SQL语句影响的记录条数
int num = this.jdbcTemplate.update(sql, id);
return num;
} // 5、通过id查询账户数据信息
public Account findAccountById(int id) { //5.1、定义SQL语句
String sql = "select * from account where id = ?"; // 5.2、创建一个新的BeanPropertyRowMapper对象
RowMapper<Account> rowMapper = new BeanPropertyRowMapper<Account>(Account.class); // 5.3、将id绑定到SQL语句中,并通过RowMapper返回一个Object类型的单行记录
return this.jdbcTemplate.queryForObject(sql, rowMapper, id);
} // 6、查询所有账户信息
public List<Account> findAllAccount() { // 6.1、定义SQL语句
String sql = "select * from account"; // 6.2、创建一个新的BeanPropertyRowMapper对象
RowMapper<Account> rowMapper = new BeanPropertyRowMapper<Account>(Account.class); // 6.3、执行静态的SQL查询,并通过RowMapper返回结果
return this.jdbcTemplate.query(sql, rowMapper);
}
}

④测试类:JdbcTemplate中添加一个测试方法addAccountTest(),用于添加用户信息:

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

⑤运行结果:

Java EE学习笔记(四)

Java EE学习笔记(四)

⑥测试类:JdbcTemplate中添加一个测试方法updateAccountTest(),用于更新用户信息:

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

⑦运行结果:

Java EE学习笔记(四)

Java EE学习笔记(四)

⑧测试类:JdbcTemplate中添加一个测试方法deleteAccountTest(),用于删除用户信息:

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

⑨运行结果:

Java EE学习笔记(四)

Java EE学习笔记(四)

4)、query()的使用

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

Java EE学习笔记(四)

b)、向数据表account中插入几条数据:

Java EE学习笔记(四)

①测试类JdbcTemplate中添加一个测试方法findAccountByIdTest(),用于查找用户id的信息:

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

②运行结果:

Java EE学习笔记(四)

③测试类JdbcTemplate中添加一个测试方法findAllAccountTest(),用于查找所有用户的信息:

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

④运行结果:

Java EE学习笔记(四)

个人总结:

如何管理用户的数据库?首先应单独写一个类来存储用户的所有信息;其次“管理员”创建实现操作用户的接口类(拥有的操作方法)以及对应的接口实现类,其中接口实现类要注入JdbcTemplate属性和它的setter方法,因为用JdbcTemplate管理数据库起来很方便,并且要实现对用户的增删查改的具体方法;然后测试操作时,首先都要加载配置文件,因为这些都由Spring容器来管理,然后获取容器中管理用户的Bean实例,若要对用户信息进行增加或更新,则要先new一个普通用户的实例,向这个实例中传入需要操作的数据,最后通过Bean实例去调用相应的操作用户的方法即可。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,494
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295