Spring黑馬:SpringIOC案例(JDBC數據庫):XML配置


整個Spring黑馬父類pom.xml配置
< modules>標籤裏是子類

<?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>com.jh</groupId>
    <artifactId>Spring_黑馬</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>Spring_Bean解耦</module>
        <module>SpringIOC</module>
        <module>SpringBean</module>
        <module>Spring依賴</module>
        <module>Spring註解</module>
        <module>SpringIOC_XML</module>
        <module>SpringIOC註解案例</module>
        <module>Spring新註解(無xml)</module>
    </modules>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.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>8.0.18</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>

1. bean.xml配置(關鍵)

下面的是層層遞進調用,通過ref屬性層層調用
(1)配置Service層
(2)配置Dao層
(3)配置QueryRunner對象
(4)配置數據源

<?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.jh.service.impl.AccountServiceImpl">
        <!--注入dao-->
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置Dao層-->
    <bean id="accountDao" class="com.jh.dao.impl.AccountDaoImpl">
        <!--注入QueryRunner對象-->
        <property name="runner" ref="runner"></property>
    </bean>

    <!--配置QueryRunner對象-->
    <bean id="runner" 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/maven?serverTimezone=GMT%2B8"></property>
        <property name="user" value="root"></property>
        <property name="password" value="jh7851192"></property>
    </bean>
</beans>

2. dao層、domain層、service層、測試類

(1)dao層

IAccountDao接口

public interface IAccountDao {
    //1. 查詢所有
    List<Account> findAllAccount();
    //2.查詢一個
    Account findAccountById(Integer accountId);
    //3.保存
    void saveAccount(Account account);
    //4.刪除操作
    void deleteAccount(Integer accountId);
    //5.更新操作
    void updateAccount(Account account);
}

AccountDaoImpl實現類

  • 這裏添加了QueryRunner對象;
  • SQL語句在持久層實現類裏寫。
public class AccountDaoImpl implements IAccountDao {
  
    private QueryRunner runner;
    public QueryRunner getRunner() {
        return runner;
    }
    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }
    @Override
    public List<Account> findAllAccount() {
        try {
            //這裏是在Spring裏應用數據庫連接(sql語句查詢);
            //Account.class是查詢的實體類關聯,這裏是List集合,用到BeanListHandler
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findAccountById(Integer accountId) {
        try {
            //Account.class是查詢的實體類關聯,這裏不是List集合,用BeanHandler
            return runner.query("select * from account where id=?",
                    new BeanHandler<Account>(Account.class),accountId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveAccount(Account account) {
        try {
            //account表中id是自增長,故不需要寫
            runner.update("insert into account(name,money)values(?,?)",
                    account.getName(),account.getMoney());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteAccount(Integer accountId) {
        try {
            //問號佔位符填的是傳入參數值accountId
            runner.update("delete from account where id=?",accountId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateAccount(Account account) {
        try {
            /*每個問號代表一個佔位符(1,2,3),後面的account.getName(),
            account.getMoney(),account.getId(),按順序排列在前面的問號裏*/
            runner.update("update account set name=?,money=? where id=?",
                    account.getName(),account.getMoney(),account.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

(2)service層
IAccountService業務層接口

public interface IAccountService {
    //1. 查詢所有
    List<Account> findAllAccount();
    //2.查詢一個
    Account findAccountById(Integer accountId);
    //3.保存
    void saveAccount(Account account);
    //4.刪除操作
    void deleteAccount(Integer accountId);
    //5.更新操作
    void updateAccount(Account account);
}

AccountServiceImpl 業務層調用持久層

public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao;

    public IAccountDao getAccountDao() {
        return accountDao;
    }

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

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

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

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

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

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

domain主體類

  • 省略了set和get,toString方法
  • 如果操作數據庫,則屬性名最好設置與(表)查詢字段表一致
package com.jh.domain;
import java.io.Serializable;
public class Account implements Serializable {
    private Integer id;
    private String name;
    private Float money;
}

測試類

public class AccountServiceTest {
    @Autowired
    private ApplicationContext ac =null;
    private IAccountService as = null;
    @Before  //省略這些重複步驟
    public void init(){
        //1.使用註解獲取容器
        ac=new ClassPathXmlApplicationContext("bean.xml");
        //2.得到業務層對象(bean對象),name的id要與bean.xml中id一樣accountService
        as = ac.getBean("accountService",IAccountService.class);
    }
    @Test
    public void testFindAll(){
        //3.執行方法
        List<Account> accounts=as.findAllAccount();
        for (Account account:accounts){
            System.out.println(account);
            /*Account{id=1, name='aaa', money=1000.0}
            Account{id=2, name='bbb', money=1000.0}
            Account{id=3, name='ccc', money=1000.0}*/
        }
    }
    @Test
    public void testFindOne(){
        //3.執行方法
        System.out.println(as.findAccountById(2));
        /*Account{id=2, name='bbb', money=1000.0}*/
    }
    @Test
    public void testSave(){
        Account account=new Account();
        account.setName("郭會技");
        account.setMoney(12782f);
        //3.執行方法
        as.saveAccount(account);
        /*Account{id=5, name='郭會技', money=12782.0}*/
    }
    @Test
    public void testUpdate(){
        //3.執行方法
        Account account=as.findAccountById(5);
        account.setMoney(12213f);
        account.setName("jh");
        as.updateAccount(account);
    }
    @Test
    public void testDelete(){
        //3.執行方法
        as.deleteAccount(4);
    }
}
發佈了95 篇原創文章 · 獲贊 15 · 訪問量 6091
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章