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

1.导入需要的maven坐标


<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.0modelVersion>

    <groupId>com.cenzngroupId>
    <artifactId>springXMLartifactId>
    <version>1.0-SNAPSHOTversion>
    
    <dependencies>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.2.5.RELEASEversion>
        dependency>

        <dependency>
            <groupId>commons-dbutilsgroupId>
            <artifactId>commons-dbutilsartifactId>
            <version>1.7version>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.19version>
        dependency>

        <dependency>
            <groupId>c3p0groupId>
            <artifactId>c3p0artifactId>
            <version>0.9.1.2version>
        dependency>

        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
        dependency>
    dependencies>
project>

2.目录结构

spring xml 配置实现数据库简单的增删改查(CRUD)_第1张图片

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


<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="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

你可能感兴趣的:(spring)