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

article/2023/6/4 14:45:31

目录

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;}@Overridepublic void save(Account account) {dbAssit.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());}@Overridepublic void update(Account account) {dbAssit.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());}@Overridepublic void delete(Integer accountId) {dbAssit.update("delete from account where id=?",accountId);}@Overridepublic Account findById(Integer accountId) {return dbAssit.query("select * from account where id=?",new BeanHandler<Account>(Account.class),accountId);}@Overridepublic 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;}@Overridepublic void saveAccount(Account account) {accountDao.save(account);}@Overridepublic void updateAccount(Account account) {accountDao.update(account);}@Overridepublic void deleteAccount(Integer accountId) {accountDao.delete(accountId);}@Overridepublic Account findAccountById(Integer accountId) {return accountDao.findById(accountId);}@Overridepublic 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/beanshttp://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/beanshttp://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 {/*** 测试保存*/@Testpublic 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);}/*** 测试查询一个*/@Testpublic void testFindAccountById() {ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");IAccountService as = ac.getBean("accountService",IAccountService.class);Account account = as.findAccountById(1);System.out.println(account);}/*** 测试更新*/@Testpublic 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);}/*** 测试删除*/@Testpublic void testDeleteAccount() {ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");IAccountService as = ac.getBean("accountService",IAccountService.class);as.deleteAccount(1);}/*** 测试查询所有*/@Testpublic 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);
        }
      • 这种方式虽然能解决问题,但是扔需要写代码来获取容器。
http://www.ngui.cc/article/show-1007676.html

相关文章

Spring - Spring 注解相关面试题总结

文章目录01. Spring 配置方式有几种&#xff1f;02. Spring 如何实现基于xml的配置方式&#xff1f;03. Spring 如何实现基于注解的配置&#xff1f;04. Spring 如何基于注解配置bean的作用范围&#xff1f;05. Spring Component, Controller, Repository, Service 注解有何区别…

2023-3-25 java选择题每日一练

继承中类, 静态代码块, 实例代码块和构造方法的执行顺序其原理如下:当没有子类继承的时候顺序&#xff1a;静态代码块 → main → 构造代码块 → 构造方法public class Test {static{System.out.println("父类静态代码块开始执行&#xff01;");}{System.out.println…

【WMS学习】从悬浮窗的添加来看窗口的add和update

这里我们从一个悬浮窗应用来查看WindowManager的addView使用&#xff0c;从这里作为突破口来认识窗口的添加&#xff0c;和窗口的位置大小更新方法updateViewLayout&#xff0c;使用WindowManager的addView方法来添加窗口非常的直观&#xff0c;因为Activity的显示中&#xff0…

领域驱动设计(Domain-Driven Design, DDD)

领域驱动设计&#xff08;Domain Driven Design&#xff0c;简称DDD&#xff09;是一种面向对象软件开发方法&#xff0c;它强调将软件系统的设计和实现过程与业务领域紧密结合&#xff0c;通过深入理解和建模业务领域&#xff0c;从而达到高内聚、低耦合的目的。 领域驱动设计…

【ChatGPT】比尔·盖茨最新分享:ChatGPT的发展,不止于此

✅作者简介&#xff1a;在读博士&#xff0c;伪程序媛&#xff0c;人工智能领域学习者&#xff0c;深耕机器学习&#xff0c;交叉学科实践者&#xff0c;周更前沿文章解读&#xff0c;提供科研小工具&#xff0c;分享科研经验&#xff0c;欢迎交流&#xff01;&#x1f4cc;个人…

【学习总结】IMU噪声的连续形式与离散形式

乱七八糟的&#xff0c;查了半天资料&#xff0c;整理如下。 &#xff08;网上其他地方的资料也很混乱&#xff0c;这篇总结是我综合比对&#xff0c;得出的结论&#xff09; 统一符号 连续形式&#xff1a; gyroscope white noise: σg\sigma_gσg​ accelerator white nois…

[puzzle-5]目标图形中拼图块能够存放的位置

有如下的八种拼图块,每块都是由八块小正方块构成, 这些拼图块刚好可以某种方式拼合放入给定的目标形状, 请以C或C++编程,自动求解 一种拼图方式 目标拼图: 从拼图块和目标图形中我们可以发现目标图形是8*8=64个方块,也就是目标图形需要使用上述8中拼图进行拼接,每个使…

CentOS挂载U盘拷贝文件

1.登录linux操作系统&#xff0c;将U盘插入主机 2.新建一个目录将U盘挂载到该目录 使用命令: mkdir /mnt/usb 3.查看可用的挂载点 使用命令&#xff1a; fdisk -l 4. 将U盘挂载到刚才建立的目录下 使用命令: mount /dev/sdb4 /mnt/usb 5.查看U盘识别情况 使用命令 &#x…

【生活工作经验 十】ChatGPT模型对话初探

最近探索了下全球大火的ChatGPT&#xff0c;想对此做个初步了解 一篇博客 当今社会&#xff0c;自然语言处理技术得到了迅速的发展&#xff0c;人工智能技术也越来越受到关注。其中&#xff0c;基于深度学习的大型语言模型&#xff0c;如GPT&#xff08;Generative Pre-train…

ES6技术总结与测试用例

一、介绍 ES6全称是ECMAScript ECMAScript 和 JavaScript 的关系 一个常见的问题是&#xff0c;ECMAScript 和 JavaScript 到底是什么关系&#xff1f; 要讲清楚这个问题&#xff0c;需要回顾历史。1996 年 11 月&#xff0c;JavaScript 的创造者 Netscape 公司&#xff0c…