本教程源码请访问:tutorial_demo
学习本篇教程之前,需要了解(会用就行)以下内容:
- 数据库连接池c3p0;
- Apache Commons DbUtils。
只学习不练习一切都是假的,接下来我们利用之前学习的IOC和DI的知识结合Apache Commons DbUtils实现单表的CRUD操作。
一、需求和技术要求
1.1、需求
实现单表的CRUD
1.2、技术要求
- 使用Spring的IOC实现对象的管理;
- 使用Spring的DI实现属性的注入;
- 使用Apache Commons DbUtils进行持久层操作;
- 使用c3p0数据库连接池。
二、实现过程
2.1、建库建表
DROP DATABASE IF EXISTS springlearn;
CREATE DATABASE springlearn;
USE springlearn;
DROP TABLE IF EXISTS account;
CREATE TABLE account (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(40) DEFAULT NULL,
money float DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4;
INSERT INTO account VALUES ('1', 'aaa', '1000');
INSERT INTO account VALUES ('2', 'bbb', '1000');
INSERT INTO account VALUES ('3', 'ccc', '1000');
INSERT INTO account VALUES ('5', 'cc', '10000');
INSERT INTO account VALUES ('6', 'abc', '10000');
INSERT INTO account VALUES ('7', 'abc', '10000');
2.2、创建Maven工程并添加相关坐标
<?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>org.codeaction</groupId>
<artifactId>account</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
2.3、编写Account实体类
package org.codeaction.domain;
import java.io.Serializable;
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
2.4、编写持久层接口IAccountDao
package org.codeaction.dao;
import org.codeaction.domain.Account;
import java.util.List;
public interface IAccountDao {
List<Account> findAll();
Account findById(Integer id);
void save(Account account);
void update(Account account);
void delete(Integer id);
}
2.5、编写持久层实现类IAccountDaoImpl
package org.codeaction.dao.impl;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.codeaction.dao.IAccountDao;
import org.codeaction.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.sql.SQLException;
import java.util.List;
public class AccountDaoImpl implements IAccountDao {
private QueryRunner queryRunner;
public void setQueryRunner(QueryRunner queryRunner) {
this.queryRunner = queryRunner;
}
@Override
public List<Account> findAll() {
List<Account> list = null;
try {
list = queryRunner.query("select * from account", new BeanListHandler<Account>(Account.class));
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
@Override
public Account findById(Integer id) {
Account account = null;
try {
account = queryRunner.query("select * from account where id = ?",
new BeanHandler<Account>(Account.class), id);
} catch (SQLException e) {
e.printStackTrace();
}
return account;
}
@Override
public void save(Account account) {
Object[] params = {account.getName(), account.getMoney()};
try {
queryRunner.update("insert into account(name, money) values(?, ?)", params);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void update(Account account) {
Object[] params = {account.getName(), account.getMoney(), account.getId()};
try {
queryRunner.update("update account set name=?, money=? where id=?", params);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void delete(Integer id) {
Object[] params = {id};
try {
queryRunner.update("delete from account where id=?", id);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2.6、编写业务层接口IAccountService
package org.codeaction.service;
import org.codeaction.domain.Account;
import java.util.List;
public interface IAccountService {
List<Account> findAll();
Account findById(Integer id);
void save(Account account);
void update(Account account);
void delete(Integer id);
}
2.7、编写业务层实现类IAccountServiceImpl
package org.codeaction.service.impl;
import org.codeaction.dao.IAccountDao;
import org.codeaction.domain.Account;
import org.codeaction.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public List<Account> findAll() {
return accountDao.findAll();
}
@Override
public Account findById(Integer id) {
return accountDao.findById(id);
}
@Override
public void save(Account account) {
accountDao.save(account);
}
@Override
public void update(Account account) {
accountDao.update(account);
}
@Override
public void delete(Integer id) {
accountDao.delete(id);
}
}
2.8、编写XML配置文件(重点)
XML配置文件在resource目录下
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置service -->
<bean id="accountService" class="org.codeaction.service.impl.AccountServiceImpl">
<!-- 通过set方法注入dao实现类的对象 -->
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置dao -->
<bean id="accountDao" class="org.codeaction.dao.impl.AccountDaoImpl">
<!-- 通过set方法注入queryRunner实现类的对象 -->
<property name="queryRunner" ref="queryRunner"></property>
</bean>
<!-- 配置queryRunner -->
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!-- 通过构造方法注入连接池 -->
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!-- 配置连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 通过set方法注入四大参数 -->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springlearn"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
</beans>
Spring配置文件是这个项目的核心,同时也是通过这个配置文件的配置实现IOC和DI。结合前面的Java代码,bean的配置通过IOC的方式由Spring容器管理,属性通过DI的方式由Spring容器注入。
2.9、编写测试类
package org.codeaction.test;
import org.codeaction.domain.Account;
import org.codeaction.service.IAccountService;
import org.codeaction.service.impl.AccountServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class MyTest {
private IAccountService accountService;
@Before
public void init() {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
accountService = context.getBean("accountService", AccountServiceImpl.class);
}
@Test
public void testFindAll() {
List<Account> accounts = accountService.findAll();
for (Account account : accounts) {
System.out.println(account);
}
}
@Test
public void testFindById() {
Account account = accountService.findById(3);
System.out.println(account);
}
@Test
public void testSave() {
Account account = new Account();
account.setName("abc");
account.setMoney(10000F);
accountService.save(account);
System.out.println(account);
}
@Test
public void testDelete() {
accountService.delete(4);
}
@Test
public void testUpdate() {
Account account = new Account();
account.setId(5);
account.setName("ab111111111c111");
account.setMoney(10000F);
accountService.update(account);
}
}
分别运行测试方法进行测试。
来源:oschina
链接:https://my.oschina.net/u/4264342/blog/4291210