Java_Spring:4. 使用 spring 的 IoC 的实现CRUD【案例】

目录

1 需求和技术要求

1.1 需求

1.2 技术要求

2 环境搭建

2.1 拷贝 jar 包

2.2 创建数据库和编写实体类

2.3 编写持久层代码

2.4 编写业务层代码

2.5 创建并编写配置文件

3 配置步骤

4 测试案例

4.1 测试类代码

4.2 分析测试了中的问题


  • 1 需求和技术要求

    • 1.1 需求

      • 实现账户的 CRUD 操作
    • 1.2 技术要求

      • 使用 spring 的 IoC 实现对象的管理
      • 使用 DBAssit 作为持久层解决方案
      • 使用 c3p0 数据源
  • 2 环境搭建

    • 2.1 拷贝 jar 包

      •  
    • 2.2 创建数据库和编写实体类

      • 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('aaa',1000);
        insert into account(name,money) values('bbb',1000);
        insert into account(name,money) values('ccc',1000);
      • /**
        * 账户的实体类
        * @Version 1.0
        */
        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;
            }
        }
    • 2.3 编写持久层代码

      • 账户的持久层接口
      • /**
        * 账户的持久层接口
        * @Version 1.0
        */
        public interface IAccountDao {
            /**
            * 保存
            * @param account
            */
            void save(Account account);
        
            /**
            * 更新
            * @param account
            */
            void update(Account account);
        
            /**
            * 删除
            * @param accountId
            */
            void delete(Integer accountId);
        
            /**
            * 根据 id 查询
            * @param accountId
            * @return
            */
            Account findById(Integer accountId);
        
            /**
            * 查询所有
            * @return
            */
            List<Account> findAll();
        }
      • 账户的持久层实现类
      • /**
        * 账户的持久层实现类
        * @Version 1.0
        */
        public class AccountDaoImpl implements IAccountDao {
            
            private DBAssit dbAssit;
            
            public void setDbAssit(DBAssit dbAssit) {
                this.dbAssit = dbAssit;
            }
        
            @Override
            public void save(Account account) {
                dbAssit.update(
              "insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
            }
        
            @Override
            public void update(Account account) {
                dbAssit.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
            }
        
            @Override
            public void delete(Integer accountId) {
                dbAssit.update("delete from account where id=?",accountId);
            }
        
            @Override
            public Account findById(Integer accountId) {
                return dbAssit.query("select * from account where id=?",
                                new BeanHandler<Account>(Account.class),accountId);
            }
        
            @Override
            public List<Account> findAll() {
                return dbAssit.query("select * from account where id=?",
                    new BeanListHandler<Account>(Account.class));
            }
        }
    • 2.4 编写业务层代码

      • 账户的业务层接口
      • public interface IAccountService {
        
            /**
            * 保存账户
            * @param account
            */
            void saveAccount(Account account);
        
            /**
            * 更新账户
            * @param account
            */
            void updateAccount(Account account);
        
            /**
            * 删除账户
            * @param account
            */
            void deleteAccount(Integer accountId);
        
            /**
            * 根据 id 查询账户
            * @param accountId
            * @return
            */
            Account findAccountById(Integer accountId);
        
            /**
            * 查询所有账户
            * @return
            */
            List<Account> findAllAccount();
        }
      • 账户的业务层实现类
      • public class AccountServiceImpl implements IAccountService {
        
            private IAccountDao accountDao;
            
            public void setAccountDao(IAccountDao accountDao) {
                this.accountDao = accountDao;
            }
        
            @Override
            public void saveAccount(Account account) {
                accountDao.save(account);
            }
        
            @Override
            public void updateAccount(Account account) {
                accountDao.update(account);
            }
        
            @Override
            public void deleteAccount(Integer accountId) {
                accountDao.delete(accountId);
            }
        
            @Override
            public Account findAccountById(Integer accountId) {
                return accountDao.findById(accountId);
            }
        
            @Override
            public List<Account> findAllAccount() {
                return accountDao.findAll();
            }
        }
    • 2.5 创建并编写配置文件

      • <?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">
        </beans>
  • 3 配置步骤

    • <?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.itheima.service.impl.AccountServiceImpl">
              <property name="accountDao" ref="accountDao"></property>
          </bean>
      
          <!-- 配置 dao -->
          <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
              <property name="dbAssit" ref="dbAssit"></property>
          </bean>
      
          <!-- 配置 dbAssit 此处我们只注入了数据源,表明每条语句独立事务-->
          <bean id="dbAssit" class="com.itheima.dbassit.DBAssit">
              <property name="dataSource" ref="dataSource"></property>
          </bean>
      
          <!-- 配置数据源 -->
          <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
              <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
              <property name="jdbcUrl" value="jdbc:mysql:///spring_day02"></property>
              <property name="user" value="root"></property>
              <property name="password" value="1234"></property>
          </bean>
      </beans>
  • 4 测试案例

    • 4.1 测试类代码

      • public class AccountServiceTest {
            /**
            * 测试保存
            */
            @Test
            public void testSaveAccount() {
                Account account = new Account();
                account.setName("黑马程序员");
                account.setMoney(100000f);
                ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
                IAccountService as = ac.getBean("accountService",IAccountService.class);
                as.saveAccount(account);
            }
        
            /**
            * 测试查询一个
            */
            @Test
            public void testFindAccountById() {
                ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
                IAccountService as = ac.getBean("accountService",IAccountService.class);
                Account account = as.findAccountById(1);
                System.out.println(account);
            }
        
            /**
            * 测试更新
            */
            @Test
            public void testUpdateAccount() {
                ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
                IAccountService as = ac.getBean("accountService",IAccountService.class);
                Account account = as.findAccountById(1);
                account.setMoney(20301050f);
                as.updateAccount(account);
            }
        
            /**
            * 测试删除
            */
            @Test
            public void testDeleteAccount() {
                ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
                IAccountService as = ac.getBean("accountService",IAccountService.class);
                as.deleteAccount(1);
            }
        
            /**
            * 测试查询所有
            */
            @Test
            public void testFindAllAccount() {
                ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
                IAccountService as = ac.getBean("accountService",IAccountService.class);
                List<Account> list = as.findAllAccount();
                for(Account account : list) {
                    System.out.println(account);
                }
            }
        }
    • 4.2 分析测试了中的问题

      • 通过上面的测试类,可以看出,每个测试方法都重新获取了一次 spring 的核心容器,造成了不必要的重复代码,增加了开发的工作量。这种情况,在开发中应该避免发生。
      • 可以考虑把容器的获取定义到类中去。例如:
      • public class AccountServiceTest {
            private ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
            private IAccountService as = ac.getBean("accountService",IAccountService.class);
        }
      • 这种方式虽然能解决问题,但是扔需要写代码来获取容器。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值