到这里,有关SpringIOC相关的知识点基本都已讲完,现在我们来做一个实际操作数据库进行数据读写的案例,此案例包括两种实现方式,即基于xml配置文件的IOC和基于注解的IOC。另外,我们还需要学习几个新的注解。

新建一个项目,主要有三个类:持久层操作数据库的的实现类、数据库查询账户的实体类、业务层的实现类。接口的代码我就忽略不贴了。具体代码如下:

1.账户实体类

该类的作用是进行对象关系映射,将查询出的记录,存储到该类的对象中。

package com.eastnotes.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 String getName() {
        return name;
    }

    public Float getMoney() {
        return money;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

2.持久层实现类

该类中使用dbutils工具进行数据库的连接,以及数据的读取操作。

package com.eastnotes.dao.impl;

import com.eastnotes.dao.AccountDao;
import com.eastnotes.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * 账户的持久层实现类
 */
public class AccountDaoImpl implements AccountDao {

    private QueryRunner runner;

    public void setRunner(QueryRunner runner){
        this.runner = runner;
    }

    public List<Account> findAllAccount() {
        try {
            return runner.query("select * from account", new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Account findAccountById(Integer id) {
        try {
            return runner.query("select * from account where id = ?", new BeanHandler<Account>(Account.class), id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void saveAccount(Account account) {
        try {
            runner.update("insert into account(name,money)values(?,?) ", account.getName(), account.getMoney());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void updateAccount(Account account) {
        try {
            runner.update("update account set name=?, money=? where id =?", account.getName(), account.getMoney(), account.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void deleteAccount(Integer id) {
        try {
            runner.update("delete from account where id = ?", id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

3.业务层实现类

该类主要是写业务逻辑,需要依赖持久成的对象,来进行实际的数据库操作。

package com.eastnotes.service.impl;

import com.eastnotes.dao.AccountDao;
import com.eastnotes.domain.Account;
import com.eastnotes.service.AccountService;

import java.util.List;

/**
 * 账户的业务层实现类
 */
public class AccountServiceImpl implements AccountService {

    private AccountDao accountDao;


    public void setAccountDao(AccountDao accountDao){
        this.accountDao = accountDao;
    }

    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    public Account findAccountById(Integer id) {
        return accountDao.findAccountById(id);
    }

    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    public void deleteAccount(Integer id) {
        accountDao.deleteAccount(id);
    }
}

4.配置xml文件

在xml配置文件中配置bean对象,并对某些对象进行依赖注入:

<?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">

    <!--配置service对象-->
    <bean id="accountService" class="com.eastnotes.service.impl.AccountServiceImpl">
        <!--使用set注入dao-->
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置DAO对象-->
    <bean id="accountDao" class="com.eastnotes.dao.impl.AccountDaoImpl">
        <!--使用set注入QueryRunner-->
        <property name="runner" ref="runner"></property>
    </bean>

    <!--配置QueryRunner对象-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner">
        <!--使用构造函数注入数据源datasource-->
        <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/spring"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
</beans>

5.进行测试

这里我们使用Junit包进行测试

package com.eastnotes.test;

import com.eastnotes.domain.Account;
import com.eastnotes.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;

/**
 * 使用Junit单元测试配置
 */
public class AccountServiceTest {

    @Test
    public void testFindAll() {
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");

        //2.得到业务层对象
        AccountService as = (AccountService)ac.getBean("accountService", AccountService.class);

        //3.执行方法
        List<Account> accounts = as.findAllAccount();
        for(Account account : accounts){
            System.out.println(account);
        }
    }

    @Test
    public void testFindOne() {
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");

        //2.得到业务层对象
        AccountService as = (AccountService)ac.getBean("accountService", AccountService.class);

        //3.执行方法
        Account account = as.findAccountById(1);

        System.out.println(account);
    }

    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("laosi");
        account.setMoney(100.12f);

        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");

        //2.得到业务层对象
        AccountService as = (AccountService)ac.getBean("accountService", AccountService.class);

        //3.执行方法
        as.saveAccount(account);
    }

    @Test
    public void testUpdate() {
        Account account = new Account();
        account.setMoney(230.12f);
        account.setName("xiangdong");
        account.setId(1);
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");

        //2.得到业务层对象
        AccountService as = (AccountService)ac.getBean("accountService");

        //3.执行方法
        as.updateAccount(account);
    }

    @Test
    public void testDelete() {
        //1.获取容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");

        //2.获取Bean对象
        AccountService as = (AccountService)ac.getBean("accountService");

        //3.执行删除的方法
        as.deleteAccount(2);
    }
}

可以看到,测试程序中有很多的重复代码,后面我们会用spring整合junit进行测试,解决这个问题。