Spring实例--XML配置实现

本实例是主要是通过Spring实现数据库的CRUD操作。
以下是主要使用到的jar包的maven坐标

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.2.1.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>commons-dbutilsgroupId>
            <artifactId>commons-dbutilsartifactId>
            <version>1.7version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.18version>
        dependency>
        
        <dependency>
            <groupId>c3p0groupId>
            <artifactId>c3p0artifactId>
            <version>0.9.1.2version>
        dependency>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>

创建实例数据表

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('熊大',5000);
insert into account(name,money) values('熊二',5000);
insert into account(name,money) values('光头强',1000);

编写持久层接口及其实现类

/**
 * 账户的持久层接口
 */
public interface AccountDao {

    /**
     * 查询所有账户
     * @return
     */
    public List<Account> findAllAccount();

    /**
     *通过账户id查询账户
     * @param accountId
     * @return
     */
    public Account findAccountById(int accountId);

    /**
     * 保存账户
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新账户信息
     */
    public void updateAccount(Account account);

    /**
     * 通过账户id删除账户
     * @param accountId
     */
    public void deleteAccount(int accountId);
}


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

    //提供对sql语句操作的API
    private QueryRunner queryRunner;

    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }

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

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

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

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

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

编写业务层接口及其实现类


/**
 * 账户业务层接口
 */
public interface AccountService {

    /**
     * 查询所有账户
     * @return
     */
    public List<Account> findAllAccount();

    /**
     *通过账户id查询账户
     * @param accountId
     * @return
     */
    public Account findAccountById(int accountId);

    /**
     * 保存账户
     */
    void saveAccount(Account account);

    /**
     * 更新账户信息
     */
    public void updateAccount(Account account);

    /**
     * 通过账户id删除账户
     * @param accountId
     */
    public void deleteAccount(int accountId);
}
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(int accountId) {
        return accountDao.findAccountById(accountId);
    }

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

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

    public void deleteAccount(int accountId) {
        accountDao.deleteAccount(accountId);
    }
}

编写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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="accountService" class="com.liang.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>
    <bean id="accountDao" class="com.liang.dao.impl.AccountDaoImpl">
        <property name="queryRunner" ref="queryRunner"></property>
    </bean>
    <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">
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mySpring?serverTimezone=UTC"></property>
        <property name="user" value="root"></property>
        <property name="password" value="liang"></property>
    </bean>
</beans>

编写测试类

public class SpringTest {

    private AccountService accountService;

    @Before
    public void init()
    {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        accountService = (AccountService)applicationContext.getBean("accountService");
        System.out.println(accountService);
    }

    @Test
    public void testFindAllAccount()
    {
        List<Account> accounts = accountService.findAllAccount();
        for (Account account:accounts)
        {
            System.out.println(account);
        }
    }

    @Test
    public void testFindAccountById()
    {
        Account account = accountService.findAccountById(1);
        System.out.println(account);
    }

    @Test
    public void testSaveAccount()
    {
        Account account = new Account();
        account.setName("灰太狼");
        account.setMoney(0.01f);
        accountService.saveAccount(account);
    }

    @Test
    public void testUpdateAccount()
    {
        Account account = accountService.findAccountById(4);
        account.setMoney(0.001f);
        accountService.updateAccount(account);
    }

    @Test
    public void testDeleteAccount()
    {
        accountService.deleteAccount(4);
    }

}

你可能感兴趣的:(Spring)