spring xml 配置实现数据库简单的增删改查(CRUD)

1.导入需要的maven坐标

<?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.cenzn</groupId>
    <artifactId>springXML</artifactId>
    <version>1.0-SNAPSHOT</version>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.7</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.19</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.12</version>
        </dependency>
    </dependencies>
</project>

2.目录结构

在这里插入图片描述

3.数据库sql

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);

4.实体类Account.java

package com.cenzn.domain;

public class Account {

    private Integer id;
    private String name;
    private Double 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 Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

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

5.业务层接口类IAccountService.java

package com.cenzn.service;

import com.cenzn.domain.Account;

import java.util.List;

public interface IAccountService {


    void saveAccount(Account account);

    void deleteAccount(Integer  accountId);

    void updateAccount(Account account);

    List<Account> findAllAccount();

    Account findAccountById(Integer  accountId);

}

6.业务层实现类AccountServiceImpl.java

package com.cenzn.service.impl;

import com.cenzn.dao.IAccoutDao;
import com.cenzn.domain.Account;
import com.cenzn.service.IAccountService;

import java.util.List;

public class AccountServiceImpl implements IAccountService {


    private IAccoutDao iAccoutDao;

    public void setiAccoutDao(IAccoutDao iAccoutDao) {
        this.iAccoutDao = iAccoutDao;
    }

    public void saveAccount(Account account) {

        iAccoutDao.saveAccount(account);
    }

    public void deleteAccount(Integer accountId) {

        iAccoutDao.deleteAccount(accountId);
    }

    public void updateAccount(Account account) {

        iAccoutDao.updateAccount(account);
    }

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


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

}

7.持久层接口类IAccountDao.java

package com.cenzn.dao;

import com.cenzn.domain.Account;

import java.util.List;

public interface IAccoutDao {

    int saveAccount(Account account);

    void deleteAccount(Integer  accountId);

    void updateAccount(Account account);

    List<Account> findAllAccount();

    Account findAccountById(Integer  accountId);
}

8.持久层实现类AccountDaoImpl.java

package com.cenzn.dao.impl;

import com.cenzn.dao.IAccoutDao;
import com.cenzn.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.util.List;

public class AccountDaoImpl implements IAccoutDao {

    private QueryRunner runner;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    public int saveAccount(Account account) {
        try{
            return runner.update("insert into account(name,money)values(?,?)" ,account.getName(),account.getMoney());
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public void deleteAccount(Integer accountId) {
        try{
            runner.update("delete from account where id = ?" ,accountId);
        }catch (Exception 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 (Exception e){
            throw new RuntimeException(e);
        }
    }


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

    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);
        }
    }
}

9.配置文件bean.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="accountService" class="com.cenzn.service.impl.AccountServiceImpl">
        <property name="iAccoutDao" ref="accountDao"/>
    </bean>

    <bean id="accountDao" class="com.cenzn.dao.impl.AccountDaoImpl">
        <property name="runner" ref="queryRunner"/>
    </bean>

    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <constructor-arg name="ds" ref="dateSource"/>
    </bean>

    <bean id="dateSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///spring?serverTimezone=UTC"/>
<!--        <property name="jdbcUrl" value="jdbc:mysql:///spring"/>-->
        <property name="user" value="root"/>
        <property name="password" value="root"/>
    </bean>


</beans>

10.测试类AccountServiceTest.java

package com.cenzn.test;

import com.cenzn.domain.Account;
import com.cenzn.service.impl.AccountServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class AccountServiceTest {
    
    @Test
    public void testFindAll(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        AccountServiceImpl accountService = ac.getBean("accountService",AccountServiceImpl.class);
        List<Account> accounts = accountService.findAllAccount();
        for(Account account : accounts){
            System.out.println(account);
        }
    }

    @Test
    public void testFindById(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        AccountServiceImpl accountService = ac.getBean("accountService",AccountServiceImpl.class);
        System.out.println(accountService.findAccountById(2));
    }

    @Test
    public void testSave(){
        Account account = new Account();
        account.setName("小小");
        account.setMoney(1200d);
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        AccountServiceImpl accountService = ac.getBean("accountService",AccountServiceImpl.class);
        accountService.saveAccount(account);
    }

    @Test
    public void testDelete(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        AccountServiceImpl accountService = ac.getBean("accountService",AccountServiceImpl.class);
        accountService.deleteAccount(4);
    }

    @Test
    public void testUpdate(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        AccountServiceImpl accountService = ac.getBean("accountService",AccountServiceImpl.class);
        Account account = accountService.findAccountById(5);
        account.setMoney(2000d);
        accountService.updateAccount(account);
    }

}

11.遇到的坑

https://blog.csdn.net/qq_43589241/article/details/105656149

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值