Spring實例--XML配置實現

本實例是主要是通過Spring實現數據庫的CRUD操作。
以下是主要使用到的jar包的maven座標

        <!--Spring開發包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>
        <!--dbutils 用於實現數據庫的JDBC操作-->
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.7</version>
        </dependency>
        <!--用於數據庫的連接-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>
        <!--c3p0 數據庫連接池-->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <!--用於測試-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </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);
    }

}
發佈了71 篇原創文章 · 獲贊 6 · 訪問量 5379
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章