【Spring】基础入门篇(七) 基于注解方式的SpringIoC实现CRUD

Spring·基础入门篇(七) 基于注解方式的SpringIoC实现CRUD


1. 需求和技术要求

1.1 需求

实现账户的 CRUD 操作

1.2 技术要求

基于注解方式使用 spring 的 IoC 实现对象的管理
使用 DBUtils 作为持久层解决方案
使用 c3p0 数据源

2. 环境搭建

2.1 创建Maven的普通工程

【Spring】基础入门篇(七) 基于注解方式的SpringIoC实现CRUD_第1张图片

2.2 导入pom.xml坐标

<dependencies>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-contextartifactId>
        <version>5.0.2.RELEASEversion>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-testartifactId>
        <version>5.0.2.RELEASEversion>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-aopartifactId>
        <version>5.0.2.RELEASEversion>
    dependency>
    <dependency>
        <groupId>commons-dbutilsgroupId>
        <artifactId>commons-dbutilsartifactId>
        <version>1.4version>
    dependency>
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>5.1.6version>
    dependency>
    <dependency>
        <groupId>c3p0groupId>
        <artifactId>c3p0artifactId>
        <version>0.9.1.2version>
    dependency>
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.12version>
    dependency>
dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.pluginsgroupId>
            <artifactId>maven-compiler-pluginartifactId>
            <configuration>
                <source>1.8source>
                <target>1.8target>
            configuration>
        plugin>
    plugins>
build>

2.3 编写数据库和编写实体类

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);
/**
 * @author: LzCc
 * @blog: https://blog.csdn.net/qq_41744145
 * @description: 账户的实体类
 */
public class Account implements Serializable {
    private Integer id;
    private String name;
    private Float money;
	// getter、setter...
	// toString...
}

2.4 编写持久层代码

/**
 * @author: LzCc
 * @blog: https://blog.csdn.net/qq_41744145
 * @description: 账户的持久层接口
 */
public interface IAccountDao {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 保存
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 删除
     * @param acccountId
     */
    void deleteAccount(Integer acccountId);
}

使用注解开发加上持久层注解@Repository(“accountDao”),使用@Autowired自动注入无需写setter

/**
 * @author: LzCc
 * @blog: https://blog.csdn.net/qq_41744145
 * @description: 账户的持久层实现类
 */
public class AccountDaoImpl implements IAccountDao {
	@Autowired
    private QueryRunner runner;
    @Override
    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public Account findAccountById(Integer accountId) {
        try{
            return runner.query("select * from account where id = ? ",new BeanHandler<Account>(Account.class),accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void saveAccount(Account account) {
        try{
            runner.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void updateAccount(Account account) {
        try{
            runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void deleteAccount(Integer accountId) {
        try{
            runner.update("delete from account where id=?",accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

2.5 编写业务层代码

/**
 * @author: LzCc
 * @blog: https://blog.csdn.net/qq_41744145
 * @description: 账户业务接口层
 */
public interface IAccountService {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();
    /**
     * 查询一个
     * @return
     */
    Account findAccountById(Integer accountId);
    /**
     * 保存
     * @param account
     */
    void saveAccount(Account account);
    /**
     * 更新
     * @param account
     */
    void updateAccount(Account account);
    /**
     * 删除
     * @param acccountId
     */
    void deleteAccount(Integer acccountId);
}

使用注解开发加上业务层@Service(“accountService”),使用@Autowired自动注入无需写setter

/**
 * @author: LzCc
 * @blog: https://blog.csdn.net/qq_41744145
 * @description: 账户的业务层实现类
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
	@Autowired
    private IAccountDao accountDao;
    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }
    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }
    @Override
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }
    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }
    @Override
    public void deleteAccount(Integer acccountId) {
        accountDao.deleteAccount(acccountId);
    }
}

3. Spring配置文件的创建编写


<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:component-scan base-package="top.lzchao">context:component-scan>
    
    <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.jdbc.Driver">property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test">property>
        <property name="user" value="root">property>
        <property name="password" value="123456">property>
    bean>
beans>

4. 编写测试类进行测试

/**
 * @author: LzCc
 * @blog: https://blog.csdn.net/qq_41744145
 * @description: 测试类
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:applicationContext.xml"})
public class AccountServiceTest {
    @Autowired
    IAccountService as;
    /**
     * 测试保存
     */
    @Test
    public void testSaveAccount() {
        Account account = new Account();
        account.setName("勒布朗詹姆斯");
        account.setMoney(100000f);
        as.saveAccount(account);
    }
    /**
     * 测试查询一个
     */
    @Test
    public void testFindAccountById() {
        Account account = as.findAccountById(1);
        System.out.println(account);
    }
    /**
     * 测试更新
     */
    @Test
    public void testUpdateAccount() {
        Account account = as.findAccountById(1);
        account.setMoney(20301050f);
        as.updateAccount(account);
    }
    /**
     * 测试删除
     */
    @Test
    public void testDeleteAccount() {
        as.deleteAccount(1);
    }
    /**
     * 测试查询所有
     */
    @Test
    public void testFindAllAccount() {
        List<Account> list = as.findAllAccount();
        for (Account account : list) {
            System.out.println(account);
        }
    }
}

你可能感兴趣的:(※开源框架专题※,#,★,Spring·基础入门篇)