首页 > 其他分享 >Spring基于注解的CRUD

Spring基于注解的CRUD

时间:2023-12-22 14:45:34浏览次数:31  
标签:account accountService Spring void CRUD Account 注解 import public

目录

Spring基于注解的CRUD

源码

代码实现

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.zjw</groupId>
    <artifactId>day02_eesy_03account_annoioc</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>17</java.version>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <encoding>UTF-8</encoding>
        <spring.version>6.1.1</spring.version>
        <jakarta.version>2.1.0</jakarta.version>
        <mysql.version>8.0.33</mysql.version>
        <dbutils.version>1.7</dbutils.version>
        <c3p0.version>0.9.1.2</c3p0.version>
        <lombok.version>1.18.30</lombok.version>
        <junit.version>4.13.2</junit.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>jakarta.annotation</groupId>
            <artifactId>jakarta.annotation-api</artifactId>
            <version>${jakarta.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>${dbutils.version}</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>${c3p0.version}</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

Dao层实现

package com.zjw.dao.impl;

import com.zjw.dao.IAccountDao;
import com.zjw.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.Lookup;
import org.springframework.stereotype.Repository;

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

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

    public QueryRunner runner;

    /**
     * 使用Lookup注解,告诉Spring这个方法需要使用查找方法注入
     * 这里直接使用@Lookup,则Spring将会依据方法返回值
     * 将它覆盖为一个在Spring容器中获取QueryRunner这个类型的bean的方法
     * 但是也可以指定需要获取的bean的名字,如:@Lookup("runner")
     * 此时,名字为runner的bean,类型必须与方法的返回值类型一致
     */
    @Lookup
    public QueryRunner getRunner(){
        return runner;
    }

    @Override
    public List<Account> findAllAccount() {
        try {
            return getRunner().query("SELECT * FROM account",new BeanListHandler<>(Account.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findAccountById(Integer accountId) {
        try {
            return getRunner().query("SELECT * FROM account WHERE id=?",new BeanHandler<>(Account.class),accountId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveAccount(Account account) {
        try {
            getRunner().update("INSERT INTO account(name,money) VALUES(?,?)",account.getName(),account.getMoney());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateAccount(Account account) {
        try {
            getRunner().update("UPDATE account SET name=?,money=? WHERE id=?",account.getName(),account.getMoney(),account.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteAccount(Integer accountId) {
        try {
            getRunner().update("DELETE FROM account WHERE id=?",accountId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

Service层实现

Java8后Resource不在javax中维护,改为了jakarta

package com.zjw.service.impl;

import com.zjw.dao.IAccountDao;
import com.zjw.domain.Account;
import com.zjw.service.IAccountService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

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

    @Resource
    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 accountId) {
        accountDao.deleteAccount(accountId);
    }
}

测试

方式一:使用Junit方式测试

package com.zjw.test;

import com.zjw.domain.Account;
import com.zjw.service.IAccountService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * 使用Junit单元测试,测试我们的配置
 */
public class AccountServiceTest {

    private  ApplicationContext ac ;

    @Before
    public void init(){
        ac = new ClassPathXmlApplicationContext("bean.xml");
    }

    /**
     * 查询所有账户
     */
    @Test
    public void testFindAll(){
        IAccountService accountService = ac.getBean("accountService", IAccountService.class);
        List<Account> accountList = accountService.findAllAccount();
        for (Account account : accountList) {
            System.out.println(account);
        }
    }

    /**
     * 根据账户id查询账户
     */
    @Test
    public void testFindAccountById(){
        IAccountService accountService = ac.getBean("accountService", IAccountService.class);
        Account account = accountService.findAccountById(1);
        System.out.println(account);
    }

    /**
     * 新建账户
     */
    @Test
    public void testSaveAccount(){
        IAccountService accountService = ac.getBean("accountService", IAccountService.class);
        Account account = new Account();
        account.setId(4);
        account.setName("zzz");
        account.setMoney(9999f);
        accountService.saveAccount(account);
    }

    /**
     * 更新账户信息
     */
    @Test
    public void testUpdateAccount(){
        IAccountService accountService = ac.getBean("accountService", IAccountService.class);
        Account account = accountService.findAccountById(4);
        System.out.println(account);
        account.setMoney(888F);
        accountService.updateAccount(account);
    }

    /**
     * 删除账户
     */
    @Test
    public void testDeleteAccount(){
        IAccountService accountService = ac.getBean("accountService", IAccountService.class);
        accountService.deleteAccount(4);
    }
}

方式二:使用@RunWith(SpringJUnit4ClassRunner.class)注解测试

package com.zjw.test;

import com.zjw.domain.Account;
import com.zjw.service.IAccountService;
import jakarta.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * 使用@RunWith测试,测试我们的配置
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:/*.xml"})
public class AccountServiceTest2 {

    @Resource
    private IAccountService accountService;

    /**
     * 查询所有账户
     */
    @Test
    public void testFindAll(){
        List<Account> accountList = accountService.findAllAccount();
        for (Account account : accountList) {
            System.out.println(account);
        }
    }

    /**
     * 根据账户id查询账户
     */
    @Test
    public void testFindAccountById(){
        Account account = accountService.findAccountById(1);
        System.out.println(account);
    }

    /**
     * 新建账户
     */
    @Test
    public void testSaveAccount(){
        Account account = new Account();
        account.setId(4);
        account.setName("zzz");
        account.setMoney(9999f);
        accountService.saveAccount(account);
    }

    /**
     * 更新账户信息
     */
    @Test
    public void testUpdateAccount(){
        Account account = accountService.findAccountById(4);
        System.out.println(account);
        account.setMoney(888F);
        accountService.updateAccount(account);
    }

    /**
     * 删除账户
     */
    @Test
    public void testDeleteAccount(){
        accountService.deleteAccount(4);
    }
}

标签:account,accountService,Spring,void,CRUD,Account,注解,import,public
From: https://www.cnblogs.com/zjw-blog/p/17921535.html

相关文章

  • Spring基于xml的CRUD
    目录基于xml的CRUD代码实现测试基于xml的CRUD源码使用C3P0连接池使用dbutils包中的QueryRunner类来对数据库进行操作代码实现pom.xml<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://ww......
  • Spring MVC 源码分析 - HandlerMapping 组件(二)之 HandlerInterceptor 拦截器
    HandlerMapping组件HandlerMapping组件,请求的处理器匹配器,负责为请求找到合适的 HandlerExecutionChain 处理器执行链,包含处理器(handler)和拦截器们(interceptors)handler 处理器是Object类型,可以将其理解成HandlerMethod对象(例如我们使用最多的 @RequestMapping 注解所标......
  • 【Java】Spring、SpringBoot、SpringCloud理解和入门
    关于Spring、SpringBoot、SpringCloud我总结了几点。Spring是轻量级的容器框架,目前大多数项目不直接使用Spring的。SpringBoot是Spring的升级版,主要应用单个微服务,关联性小的项目、规模小、硬件要求不高的项目。SpringCloud基于SpringBoot来实现微服务开发组件。主要应用于规......
  • Spring学习记录之Spring概述
    Spring学习记录之Spring概述前言这篇文章是我第二次学习b站老杜的spring相关课程所进行的学习记录,算是对课程内容及笔记的二次整理,以自己的理解方式进行二次记录,其中理解可能存在错误,欢迎且接受各位大佬们的批评指正;关于本笔记,只是我对于相关知识遗忘时快速查阅了解使用,至于课......
  • SpringMVC处理Java8新日期类参数
    SpringMVC如何将request参数自动封装为LocalDate和LocalDateTime在使用SpringMVC时,java.util.Date类型字段可以使用@DateTimeFormat注解将application/x-www-from-urlencoded类型的请求中的字符串进行自动转换。而Java8中新的时间类型该如何支持呢?在application/x-www-from-u......
  • Spring学习记录之Spring启示录
    Spring学习记录之Spring启示录前言这篇文章是我第二次学习b站老杜的spring相关课程所进行的学习记录,算是对课程内容及笔记的二次整理,以自己的理解方式进行二次记录,其中理解可能存在错误,欢迎且接受各位大佬们的批评指正;学习视频地址:https://www.bilibili.com/video/BV1Ft4y1g7......
  • 5分钟攻略Spring-Retry框架实现经典重试场景
    前言今天分享干货,控制了篇幅,5分钟内就能看完学会。主题是Spring-Retry框架的应用,做了一个很清晰的案例,代码可下载自测。框架介绍Spring-Retry框架是Spring自带的功能,具备间隔重试、包含异常、排除异常、控制重试频率等特点,是项目开发中很实用的一种框架。本篇所用框架的版本......
  • Spring-IOC
     1.前言1) 框架:spring的本质就是一个容器,放java对象的容器,java对象在spring容器中也叫做bean对象。项目启动的时候,把bean对象放到IOC容器中,当需要使用对象的时候,直接从容器中拿出来使用。2) 框架作用:提高开发效率;增强可重用性;提供编......
  • 【SpringBootWeb入门-17】Mybatis-基础操作-动态SQL
    1、章节回顾上一篇文章我们讲解完了Mybatis基础操作,本篇继续学习Mybatis中非常重要的功能:动态SQL。什么是动态SQL:随着用户的输入或外部条件的变化而变化的SQL语句,我们称为动态SQL。简单说SQL语句不是固定的,是动态变化的。就拿我们上一篇所提到的根据条件来查询员工的SQL语句来......
  • Spring Boot学习随笔- 拦截器实现和配置(HandlerInterceptor、addInterceptors)、jar包
    学习视频:【编程不良人】2021年SpringBoot最新最全教程第十三章、拦截器拦截器:Interceptor拦截中断类似于javaweb中的Filter,不过没有Filter那么强大作用SpringMVC的拦截器是一种用于在请求处理过程中进行预处理和后处理的机制。拦截器可以在请求到达控制器之前和......