Spring笔记7 基于注解的IoC案例(实现CRUD)

https://www.bilibili.com/video/av47952931?p=38


数据库部分

继续用上次的表


在基于xml的案例上修改

(加上整合junit的部分,具体记录在笔记8)

pom.xml加上整合junit需要的依赖spring-test
junit版本4.12及以上

beans.xml名称空间需要修改
在Spring文档中搜索xmlns:context(基于xml时是xmlns)找名称空间
配置Service和Dao的部分可以不要了
加上component-scan告知Spring在创建容器时要扫描的包

实体类、接口没有变化

业务层实现类AccountServiceImpl加注解
@Service(“accountService”)
变量accountDao上加注解,由于只有一个AccountDao,可以用@Autowired
对应的set方法可以删掉

持久层实现类AccountDaoImpl加注解
@Repository(“accountDao”)
runner同样用@Autowired,set方法删掉

测试类改为整合junit的写法


完整代码

项目结构

pom.xml

<?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.coconutnut</groupId>
    <artifactId>day02_02_account_xml</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--    打成jar包-->
    <packaging>jar</packaging>

    <!--    加入依赖-->
    <dependencies>
        <!--        spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

    	<!--    	spring整合junit-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <!--        dbutils-->
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.4</version>
        </dependency>

        <!--        mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>

        <!--        jdbc连接池-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

        <!--    junit测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

</project>

beans.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

    <!--    告知Spring在创建容器时要扫描的包-->
    <context:component-scan base-package="com.cc"></context:component-scan>

    <!--    配置QueryRunner(多例)-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--        注入数据源(没有set方法,只能构造函数注入)-->
        <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/groot?characterEncoding=utf8"></property>
        <property name="user" value="root"></property>
        <property name="password" value="iamgroot"></property>
    </bean>

</beans>

实体类

Account.java

package com.cc.domain;

import java.io.Serializable;

/**
 * 账户的实体类
 */
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;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

业务层

IAccountService.java

package com.cc.service;

import com.cc.domain.Account;

import java.util.List;

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

    /**
     * 增
     * @param account
     */
    void createAccount(Account account);

    /**
     * 删
     * @param accountId
     */
    void deleteAccount(Integer accountId);

    /**
     * 改
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 查一个
     * @param accountId
     * @return
     */
    Account retrieveAccountById(Integer accountId);

    /**
     * 查所有
     * @return
     */
    List<Account> retrieveAllAccounts();

}

AccountServiceImpl.java

package com.cc.service.impl;

import com.cc.dao.IAccountDao;
import com.cc.domain.Account;
import com.cc.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 账户的业务层实现类
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao accountDao;

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

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

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

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

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

持久层

IAccountDao.java

package com.cc.dao;

import com.cc.domain.Account;

import java.util.List;

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

    void createAccount(Account account);

    void deleteAccount(Integer accountId);

    void updateAccount(Account account);

    Account retrieveAccountById(Integer accountId);

    List<Account> retrieveAllAccounts();

}

AccountDaoImpl.java

package com.cc.dao.impl;

import com.cc.dao.IAccountDao;
import com.cc.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

/**
 * 账户的持久层实现类
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    private QueryRunner runner;

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

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

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

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

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

}

测试方法

AccountServiceTest.java

package com.cc.test;

import com.cc.domain.Account;
import com.cc.service.IAccountService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * 使用Junit测试配置
 * Spring整合Junit的配置
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:beans.xml")
public class AccountServiceTest {

    @Autowired
    private IAccountService as;

    @Test
    public void testCreate(){
        Account account = new Account();
        account.setName("eee");
        account.setMoney(10000f);
        as.createAccount(account);
    }

    @Test
    public void testDelete(){
        as.deleteAccount(1);
    }

    @Test
    public void testUpdate(){
        Account account = as.retrieveAccountById(3);
        account.setMoney(3000f);
        as.updateAccount(account);
    }

    @Test
    public void testRetrieveOne(){
        Account account = as.retrieveAccountById(1);

        System.out.println(account);
    }

    @Test
    public void testRetrieveAll(){
        List<Account> accounts = as.retrieveAllAccounts();

        for(Account account : accounts){
            System.out.println(account);
        }
    }

}

测试

testRetrieveAll()

testRetrieveOne()

testCreate()

testDelete()

testUpdate()

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值