简介
- 本文将在 Spring 框架中,分别使用使用“XML”,“XML+注解”和“注解”三种方式来实现数据库的CRUD操作。实现数据库的CRUD操作的功能属于另外一部分的知识点,三种方式的不同点主要在于如何注入依赖。
- 基于xml配置文件
- 依赖注入:xml配置文件
- 开启注解扫描:xml配置文件
- 基于xml配置文件和注解
- 依赖注入:注解
- 开启注解扫描:注解、xml配置文件
- 基于注解
- 依赖注入:注解
- 开启注解扫描:Java配置文件
- 基于xml配置文件
项目环境
数据库代码
- 创建数据库spring,在数据库中创建 Account表。
# 创建数据库
CREATE DATABASE spring;
# 使用数据库
USE spring;
# 创建表
CREATE TABLE account(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(40),
money FLOAT
)CHARACTER SET utf8 COLLATE utf8_general_ci;
# 插入数据
INSERT INTO account(NAME,money) VALUES('Cat',1000);
INSERT INTO account(NAME,money) VALUES('Dog',1000);
INSERT INTO account(NAME,money) VALUES('Rat',1000);
Maven依赖
<dependencies>
<!-- Spring 框架 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!-- MySQL数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- 操作数据库的工具包 -->
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.4</version>
</dependency>
<!-- Spring 测试 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
基于xml配置文件
- 此部分分为三部分
- 目录结构:帮助了解整个项目的基本结构,以及完整详细的代码。
- 依赖注入:此部分是本文着重比较的地方,单独分为一部分。
- CURD操作:与Spring框架的核心内容关系不大,可作为延展内容。
目录结构
- src
- main
- java
- domain
- Account.java(实体类)
- service
- AccountService.java(业务层接口)
- AccountServiceImp.java(业务层实现类)
- dao
- AccountDao.java(持久层接口)
- AccountDaoImp.java(持久层实习类)
- domain
- resources
- Beans.xml(Spring配置文件)
- java
- test
- SpringTest.java(测试类)
- main
实体类
- 实体类根据数据库表中的字段来设置成员变量。
Account.java
package xml.domain;
public class Account {
/* 成员变量 */
private int id;
private String name;
private float money;
/* 构造函数 */
public Account() {
}
public Account(int id, String name, float money) {
this.id = id;
this.name = name;
this.money = money;
}
/* 设值函数 */
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getMoney() {
return money;
}
public void setMoney(float money) {
this.money = money;
}
/* toString方法 */
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
业务层
- 由于此案例是为了演示操作数据库的CRUD方法,所以业务层并没有实现具体功能,而只是注入了持久层接口,调用了持久层方法。
AccountService.java
package xml.service;
import xml.domain.Account;
import java.util.List;
/**
* @author Water
* @date 2019/10/24 - 8:50
* @description 业务层接口
*/
public interface AccountService {
/** 查询所有 */
List<Account> findAll();
/** 查询单个 */
Account findByID(int id);
/** 添加 */
void add(Account account);
/** 修改 */
void update(Account account);
/** 删除 */
void delete(int id);
}
AccountServiceImp.java
package xml.service;
import xml.dao.AccountDao;
import xml.domain.Account;
import java.util.List;
/**
* @author Water
* @date 2019/10/24 - 8:51
* @description 业务层实现类
*/
public class AccountServiceImp implements AccountService {
/* 成员变量 */
private AccountDao dao;
/* 设值方法 */
public void setDao(AccountDao dao) {
this.dao = dao;
}
/** 查询所有 */
public List<Account> findAll() {
return dao.findAll();
}
/** 查询单个 */
public Account findByID(int id) {
return dao.findByID(id);
}
/** 添加 */
public void add(Account account) {
dao.add(account);
}
/** 修改 */
public void update(Account account) {
dao.update(account);
}
/** 删除 */
public void delete(int id) {
dao.delete(id);
}
}
持久层
AccountDao.java
package xml.dao;
import xml.domain.Account;
import java.util.List;
/**
* @author Water
* @date 2019/10/24 - 8:50
* @description 持久层接口:实现数据库具体的CRUD操作
*/
public interface AccountDao {
/** 查询所有 */
List<Account> findAll();
/** 查询单个 */
Account findByID(int id);
/** 添加 */
void add(Account account);
/** 修改 */
void update(Account account);
/** 删除 */
void delete(int id);
}
AccountDaoImp.java
package xml.dao;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import xml.domain.Account;
import java.sql.SQLException;
import java.util.List;
/**
* @author Water
* @date 2019/10/24 - 8:52
* @description 持久层实现类:实现数据库具体的CRUD操作
*/
public class AccountDaoImp implements AccountDao {
/* 成员方法 */
private QueryRunner queryRunner;
/* 设值方法 */
public void setQueryRunner(QueryRunner queryRunner) {
this.queryRunner = queryRunner;
}
/** 查询所有 */
public List<Account> findAll() {
try {
/* QueryRunner.query */
return queryRunner.query(
/* SQL语句 */
"SELECT * FROM account ",
/* 结果集 */
new BeanListHandler<Account>(Account.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/** 查询单个 */
public Account findByID(int id) {
try {
/* QueryRunner.query */
return queryRunner.query(
/* SQL语句 */
"SELECT * FROM account WHERE id = ? ",
/* 结果集 */
new BeanHandler<Account>(Account.class),
id);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/** 添加 */
public void add(Account account) {
try {
/* QueryRunner.update */
queryRunner.update(
/* SQL语句 */
"INSERT INTO account VALUES(?,?,?)",
/* 参数 */
account.getId(),
account.getName(),
account.getMoney());
} catch (SQLException e) {
e.printStackTrace();
}
}
/** 修改 */
public void update(Account account) {
try {
/* QueryRunner.update */
queryRunner.update(
/* SQL语句 */
" UPDATE account SET name=?,money=? WHERE id=? ",
/* 参数 */
account.getName(),
account.getMoney(),
account.getId());
} catch (SQLException e) {
e.printStackTrace();
}
}
/** 删除 */
public void delete(int id) {
try {
/* QueryRunner.update */
queryRunner.update(
/* SQL语句 */
" DELETE FROM account WHERE id=? ",
/* 参数 */
id);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
配置文件
Beans.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.xsd">
<!-- DataSource -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- QueryRunner:注入DataSource -->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!-- DaoImp:注入QueryRunner -->
<bean id="daoImp" class="xml.dao.AccountDaoImp">
<property name="queryRunner" ref="runner"></property>
</bean>
<!-- ServiceImp:注入DaoImp -->
<bean id="serviceImp" class="xml.service.AccountServiceImp">
<property name="dao" ref="daoImp"></property>
</bean>
</beans>
测试类
SpringTest.java
package test.xml;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import xml.domain.Account;
import xml.service.AccountService;
/**
* @author Water
* @date 2019/10/24 - 10:07
* @description
*/
public class SpringTest {
/* 成员变量 */
private ApplicationContext app;
private AccountService service;
@Before
public void init(){
app = new ClassPathXmlApplicationContext("xml/Beans.xml");
service = app.getBean("serviceImp",AccountService.class);
}
/** 查询所有 */
@Test
public void test01() {
for (Account account : service.findAll()) {
System.out.println(account);
}
}
/** 查询单个 */
@Test
public void test02() {
System.out.println(service.findByID(1));
}
/** 添加 */
@Test
public void test03() {
service.add( new Account(4,"pig",39.11F) );
}
/** 修改 */
@Test
public void test04() {
service.update( new Account(4,"pig",9999.11F) );
}
/** 删除 */
@Test
public void test05() {
service.delete(4);
}
}
依赖注入
基于xml的方式
- ServiceImp
- Dao(设值函数)
- DaoImp
- QueryRunner(设值函数)
- QueryRunner
- DataSource(构造函数)
<!-- DataSource -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- QueryRunner:注入DataSource -->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!-- DaoImp:注入QueryRunner -->
<bean id="daoImp" class="xml.dao.AccountDaoImp">
<property name="queryRunner" ref="runner"></property>
</bean>
<!-- ServiceImp:注入DaoImp -->
<bean id="serviceImp" class="xml.service.AccountServiceImp">
<property name="dao" ref="daoImp"></property>
</bean>
CRUD操作
查询所有用户
持久层接口
List<Account> findAll();
持久层实现类
public List<Account> findAll() {
try {
/* QueryRunner.query */
return queryRunner.query(
/* SQL语句 */
"SELECT * FROM account ",
/* 结果集 */
new BeanListHandler<Account>(Account.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
根据ID查询用户
持久层接口
Account findByID(int id);
持久层实现类
public Account findByID(int id) {
try {
/* QueryRunner.query */
return queryRunner.query(
/* SQL语句 */
"SELECT * FROM account WHERE id = ? ",
/* 结果集 */
new BeanHandler<Account>(Account.class),
id);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
添加用户
持久层接口
void add(Account account);
持久层实现类
public void add(Account account) {
try {
/* QueryRunner.update */
queryRunner.update(
/* SQL语句 */
"INSERT INTO account VALUES(?,?,?)",
/* 参数 */
account.getId(),
account.getName(),
account.getMoney());
} catch (SQLException e) {
e.printStackTrace();
}
}
修改用户
持久层接口
void update(Account account);
持久层实现类
public void update(Account account) {
try {
/* QueryRunner.update */
queryRunner.update(
/* SQL语句 */
" UPDATE account SET name=?,money=? WHERE id=? ",
/* 参数 */
account.getName(),
account.getMoney(),
account.getId());
} catch (SQLException e) {
e.printStackTrace();
}
}
删除用户
持久层接口
void delete(int id);
持久层实现类
public void delete(int id) {
try {
/* QueryRunner.update */
queryRunner.update(
/* SQL语句 */
" DELETE FROM account WHERE id=? ",
/* 参数 */
id);
} catch (SQLException e) {
e.printStackTrace();
}
}
基于xml配置文件和注解
此部分分为两部分
- 目录结构:帮助了解整个项目的基本结构、如果想要阅读项目完整详细的代码,请阅读“基于xml配置文件”内容。此部分仅展示在“基于xml配置文件”基础上更新的详细代码。
- 依赖注入:此部分是本文着重比较的地方,单独分为一部分。
目录结构
- src
- main
- java
- domain
- Account.java(实体类)
- service
- AccountService.java(业务层接口)
- AccountServiceImp.java(业务层实现类)
- dao
- AccountDao.java(持久层接口)
- AccountDaoImp.java(持久层实习类)
- domain
- resources
- Beans.xml(Spring配置文件)
- java
- test
- SpringTest.java(测试类)
- main
业务层 实现类
AccountServiceImp.java
package xml_anno.service;
import org.springframework.stereotype.Component;
import xml_anno.dao.AccountDao;
import xml_anno.domain.Account;
import javax.annotation.Resource;
import java.util.List;
/**
* @author Water
* @date 2019/10/24 - 8:51
* @description 业务层实现类
*/
@Component("serviceImp")
public class AccountServiceImp implements AccountService {
/* 成员变量 */
@Resource(name = "daoImp")
private AccountDao dao;
/** 查询所有 */
public List<Account> findAll() {
return dao.findAll();
}
/** 查询单个 */
public Account findByID(int id) {
return dao.findByID(id);
}
/** 添加 */
public void add(Account account) {
dao.add(account);
}
/** 修改 */
public void update(Account account) {
dao.update(account);
}
/** 删除 */
public void delete(int id) {
dao.delete(id);
}
}
持久层 实现类
AccountDaoImp.java
package xml_anno.dao;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.stereotype.Component;
import xml_anno.domain.Account;
import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;
/**
* @author Water
* @date 2019/10/24 - 8:52
* @description 持久层实现类:实现数据库具体的CRUD操作
*/
@Component("daoImp")
public class AccountDaoImp implements AccountDao {
/* 成员方法 */
@Resource(name = "runner")
private QueryRunner queryRunner;
/** 查询所有 */
public List<Account> findAll() {
try {
/* QueryRunner.query */
return queryRunner.query(
/* SQL语句 */
"SELECT * FROM account ",
/* 结果集 */
new BeanListHandler<Account>(Account.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/** 查询单个 */
public Account findByID(int id) {
try {
/* QueryRunner.query */
return queryRunner.query(
/* SQL语句 */
"SELECT * FROM account WHERE id = ? ",
/* 结果集 */
new BeanHandler<Account>(Account.class),
id);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/** 添加 */
public void add(Account account) {
try {
/* QueryRunner.update */
queryRunner.update(
/* SQL语句 */
"INSERT INTO account VALUES(?,?,?)",
/* 参数 */
account.getId(),
account.getName(),
account.getMoney());
} catch (SQLException e) {
e.printStackTrace();
}
}
/** 修改 */
public void update(Account account) {
try {
/* QueryRunner.update */
queryRunner.update(
/* SQL语句 */
" UPDATE account SET name=?,money=? WHERE id=? ",
/* 参数 */
account.getName(),
account.getMoney(),
account.getId());
} catch (SQLException e) {
e.printStackTrace();
}
}
/** 删除 */
public void delete(int id) {
try {
/* QueryRunner.update */
queryRunner.update(
/* SQL语句 */
" DELETE FROM account WHERE id=? ",
/* 参数 */
id);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
配置文件
Beans.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 开启注解扫描 -->
<context:component-scan base-package="xml_anno"></context:component-scan>
<!-- DataSource -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- QueryRunner:注入DataSource -->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
</beans>
测试类
SpringTest.java
package test.xml_anno;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import xml_anno.domain.Account;
import xml_anno.service.AccountService;
/**
* @author Water
* @date 2019/10/24 - 10:07
* @description
*/
public class SpringTest {
/* 成员变量 */
private ApplicationContext app;
private AccountService service;
@Before
public void init(){
app = new ClassPathXmlApplicationContext("xml_anno/Beans.xml");
service = app.getBean("serviceImp",AccountService.class);
}
/** 查询所有 */
@Test
public void test01() {
for (Account account : service.findAll()) {
System.out.println(account);
}
}
/** 查询单个 */
@Test
public void test02() {
System.out.println(service.findByID(1));
}
/** 添加 */
@Test
public void test03() {
service.add( new Account(4,"pig",39.11F) );
}
/** 修改 */
@Test
public void test04() {
service.update( new Account(4,"pig",9999.11F) );
}
/** 删除 */
@Test
public void test05() {
service.delete(4);
}
}
依赖注入
基于注解的方式
- ServiceImp
- Dao(设值函数)
- DaoImp
- QueryRunner(设值函数)
ServiceImp
@Component("serviceImp")
public class AccountServiceImp implements AccountService {
/* 成员变量 */
@Resource(name = "daoImp")
private AccountDao dao;
}
DaoImp
@Component("daoImp")
public class AccountDaoImp implements AccountDao {
@Resource(name = "runner")
private QueryRunner queryRunner;
}
基于xml的方式
-
开启注解支持
-
QueryRunner
- DataSource(构造函数)
<!-- 开启注解扫描 -->
<context:component-scan base-package="xml_anno"></context:component-scan>
<!-- DataSource -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
=</bean>
<!-- QueryRunner:注入DataSource -->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
基于注解
- 目录结构:帮助了解整个项目的基本结构、如果想要阅读项目完整详细的代码,请阅读“基于xml配置文件”内容。此部分仅展示在“基于xml配置文件和注解”基础上更新的详细代码。
- 依赖注入:此部分是本文着重比较的地方,单独分为一部分。
目录结构
- src
- main
- java
- config
- SpringConfiguration.java(Java配置文件)
- domain
- Account.java(实体类)
- service
- AccountService.java(业务层接口)
- AccountServiceImp.java(业务层实现类)
- dao
- AccountDao.java(持久层接口)
- AccountDaoImp.java(持久层实习类)
- config
- resources
- jdbcConfiguration.properties(数据库连接参数)
- java
- test
- SpringTest.java(测试类)
- main
Java配置文件
package java_anno.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
/**
* @author Water
* @date 2019/10/24 - 11:57
* @description 基于纯注解方式的Java配置文件
*/
/** 指定配置文件 */
@Configuration
/** 开启注解扫描 */
@ComponentScan("java_anno")
/** 指定property文件 */
@PropertySource("classpath:java_anno/jdbcConfig.properties")
public class SpringConfiguration {
/* 定义容器 */
@Bean("runner")
/* 作用范围 */
@Scope("prototype")
/* 返回值类型:容器类型 | 方法名称:无所谓 | 参数:类成员 | @Qualifier注解:指定容器id */
public QueryRunner getQueryRunner( @Qualifier("dataSource")DataSource getDS){
/* 返回值:容器 */
return new QueryRunner(getDS);
}
/** 数据库连接参数 */
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/* 定义容器 */
@Bean("dataSource")
/* 返回值类型:容器类型 | 方法名称:无所谓 | 参数:类成员 */
public DataSource getDataSource(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
return dataSource;
}
}
数据库连接文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=root
依赖注入
基于注解
- ServiceImp
- Dao(设值函数)
- DaoImp
- QueryRunner(设值函数)
- QueryRunner
- DataSource(构造函数)
ServiceImp
@Component("serviceImp")
public class AccountServiceImp implements AccountService {
/* 成员变量 */
@Resource(name = "daoImp")
private AccountDao dao;
}
DaoImp
@Component("daoImp")
public class AccountDaoImp implements AccountDao {
@Resource(name = "runner")
private QueryRunner queryRunner;
}
QueryRunner
/* 定义容器 */
@Bean("runner")
/* 作用范围 */
@Scope("prototype")
/* 返回值类型:容器类型 | 方法名称:无所谓 | 参数:类成员 | @Qualifier注解:指定容器id */
public QueryRunner getQueryRunner( @Qualifier("dataSource")DataSource getDS){
/* 返回值:容器 */
return new QueryRunner(getDS);
}
DataSource
/** 数据库连接参数 */
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/* 定义容器 */
@Bean("dataSource")
/* 返回值类型:容器类型 | 方法名称:无所谓 | 参数:类成员 */
public DataSource getDataSource(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
return dataSource;
}