Spring整合mybatis和Junit单元测试

2023-11-04

1.Spring整合mybatis

前提了解:

spring 管理 mybatis    

mybatis 管理 mapper

要依赖于德鲁伊连接池

spring 管理sqlsessionfactory 
思路
 Spring整合Mybatis主要做两件事:

1.使用Spring管理MyBatis中的SqlSessionFactory

2.使用Spring管理Mapper接口的扫描

主要使用MybatisConfig配置文件中的SqlSessionFactoryBean和MapperScannerConfigurer这两个类来完成
1.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>org.example</groupId>
    <artifactId>spring_mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>
 <!--导入jdk版本-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
  <!--导入spring的坐标spring-context,对应版本是5.2.10.RELEASE-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
  <!--导入druid-->     
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>
<!--导入mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
 <!--导入mysql 对应版本是5.1.46RELEASE-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
<!--导入spring整理jdbc的依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
<!--导入spring整理mybatis的依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>

    </dependencies>
</project>
2.准备service和dao层基础代码
//service
public interface AccountService {

    void save(Account account);

    void delete(Integer id);

    void update(Account account);

    List<Account> findAll();

    Account findById(Integer id);

}
//service实现类
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

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

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

    public void delete(Integer id) {
        accountDao.delete(id);
    }

    public Account findById(Integer id) {
        return accountDao.findById(id);
    }

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


//dao
public interface AccountDao {

    @Insert("insert into tbl_account(name,money)values(#{name},#{money})")
    void save(Account account);

    @Delete("delete from tbl_account where id = #{id} ")
    void delete(Integer id);

    @Update("update tbl_account set name = #{name} , money = #{money} where id = #{id} ")
    void update(Account account);

    @Select("select * from tbl_account")
    List<Account> findAll();

    @Select("select * from tbl_account where id = #{id} ")
    Account findById(Integer id);
}
3.在resources下创建

jdbc.prepertios

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false
jdbc.username=root
jdbc.password=320321
4.创建JdbcConfig配置DataSource数据源
//注入第三方数据源 jdbc.properties的数据
public class JdbcConfig {
    //私有四个数据  加value获取
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("{jdbc.password}")
    private String password;

    @Bean //加注解bean 表示当前方法的返回值是一个bean对象,添加到IOC容器中
    //直接创建数据源  添加四大金刚 返回对象
    public DataSource dataSource() {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }
}
5.在config创建核心配置类
@Configuration  //表名自身是核心配置类
@ComponentScan("com.itheima")  //扫包
@PropertySource("classpath:jdbc.properties") //读取properties配置文件
@Import({JdbcConfig.class,MybatisConfig.class}) //快速导入
public class SpringConfig {
}
6.创建MybatisConfig整合mybatis.xml
//mybatisconfig.java代替mybatisconfig.xml文件的操作
public class MyBatisConfig {
    //定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象
    @Bean              //使用@bean注解 注入引用类型 在形参加对应的参数
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
         //需要代替mybatis_config.xml的文件
        //设置类型别名的包
         ssfb.setTypeAliasesPackage("com.itheima.domain");
        //替代dataSource  设置数据源  先在加形参
        ssfb.setDataSource(dataSource);
     return ssfb;
    }
    //设置代理对象
    //定义bean,返回MapperScannerConfigurer对象
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.itheima.dao");
        return msc;
    }
}
7.定义测试类进行测试
public class App {
    public static void main(String[] args) {
        //基于配置文件
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        //获取bean
        AccountService bean = context.getBean(AccountService.class);
        Account byId = bean.findById(2);
        System.out.println(byId);
    }
}

2.Spring整合Junit单元测试

主要是两个注解

//使用Spring整合Junit专用的类加载器
@RunWith(SpringJUnit4ClassRunner.class) //spring专用类
@ContextConfiguration(classes= SpringConfig.class) //加载配置类  注意要加classes
.导入整合的依赖坐标spring-test
<!--junit-->
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
</dependency>
<!--spring整合junit-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>5.1.9.RELEASE</version>
</dependency>
2.在test创建com.itheima.service
//1.使用Spring整合Junit专用的类加载器
@RunWith(SpringJUnit4ClassRunner.class) //spring专用类
@ContextConfiguration(classes= SpringConfig.class) //加载配置类  注意要加classes
public class AccountServiceTest {
//自动装配
    @Autowired
    private  AccountService accountService;

    @Test
    public void testFindAll(){
        List<Account> accounts = accountService.findAll();
        System.out.println(accounts);
    }

    @Test
    public void testFindById(){
        System.out.println(accountService.findById(1));
    }

}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring整合mybatis和Junit单元测试 的相关文章

  • org.dbunit.dataset.NoSuchTableException,但表存在

    H2 1 4 191 数据库单元 2 5 1 如何解决这个问题 3种情况的代码和结果 org dbunit dataset NoSuchTableException category org dbunit dataset NoSuchTab
  • Mybatis 期望 selectOne() 返回一个结果(或 null),但发现:190

    我正在尝试从数据库检索值 但无法获取所有值 我正进入 状态TooManyResultsException 映射器接口 这是我正在调用的映射器接口 public interface ITranslatorDAO Map
  • Selenium Webdriver:处理 NoSuchElementException 的最佳实践

    经过大量搜索和阅读后 我仍然不清楚使用 Webdriver 处理失败断言的最佳方法 我本以为这是一个常见且核心的功能 我想做的就是 寻找一个元素 如果在场 告诉我 如果不在场 告诉我 我想向非技术受众展示结果 因此让它抛出带有完整堆栈跟踪的
  • 在单独的项目中创建单元测试是 Android 的正确方法吗?

    关于如何开始在 Android 中进行测试的描述似乎不一致 http developer android com guide topics testing testing android html http developer androi
  • Spring 测试 DBunit 警告

    我正在使用 spring test dbunit 并且在单元测试中收到一条警告 其中包含以下消息 Code RunWith SpringJUnit4ClassRunner class ContextConfiguration locatio
  • ant-找不到符号@Test

    我正在尝试编译以下仅包含一个函数的类 公共类测试注释 Test public void testLogin System out println Testing Login 当我将文件作为 JUNIt 运行时 它可以工作 但是当我尝试从 b
  • JUnit 测试 Spymemcached 客户端

    我有一个类围绕spymemcached 客户端 我想编写一些JUnit 测试来测试getValue 和addKey 方法是否有效 问题是无法从测试服务器访问spymemcached 服务器 所以我想这里需要一些模拟 我的简化类看起来像这样
  • Spring JUnit 测试未加载完整的应用程序上下文

    您好 我正在尝试使用 spring junit 测试用例 并且我需要加载完整的应用程序上下文 然而 junit 测试不会初始化完整的应用程序上下文 测试类 RunWith SpringJUnit4ClassRunner class Spri
  • 使用 Ant 运行 JUnit 测试

    我正在尝试运行我的 JUnit 测试用例 但我不断收到错误 Test com capscan accentsWorld FAILED 报告已创建 但测试未运行 这是我的蚂蚁代码
  • jUnit 中的 CollectionAssert?

    是否有与 NUnit 并行的 jUnit 使用 JUnit 4 4 您可以使用assertThat 与Hamcrest http hamcrest org JavaHamcrest 代码 不用担心 它是随 JUnit 一起提供的 不需要额外
  • 使用java进行JSON模式验证[关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我正在为返回 JSON 对象的 java webapp 编写一些验收测试 我想验证返回的 JSON 是否针对架构进行验证 任何人都可以建议
  • 如何在 JUnit5 中为测试套件设置自定义测试执行顺序?

    我在 JUnit5 上进行了大量测试 并在多个线程中并行运行 还有有关每次测试时间的信息 我想在最长的测试开始时运行 并将最快的测试留在最后以优化公共执行时间 我还没有找到在 JUnit5 中执行此操作的方法 版本中5 4有一个org ju
  • 如何为Spring测试创建TestContext?

    我有一个相对较小的 Java 库 它实现了几十个 bean 没有数据库或 GUI 我创建了一个 Spring Bean 配置文件 其他 Java 项目使用该文件将我的 bean 注入到他们的东西中 我现在第一次尝试使用 Spring Tes
  • JUnit 使用 Mockito 测试异步方法

    我已经使用 Spring Framework 版本 5 0 5 RELEASE 在 Java 1 8 类中实现了异步方法 public class ClassToBeTested Autowired private MyComponent
  • 为什么尝试使用 Hamcrest 的 hasItems 的代码无法编译?

    为什么这个不能编译 哦 怎么办 import static org junit Assert assertThat import static org junit matchers JUnitMatchers hasItems ArrayL
  • 是否可以对 JUnit 中的每个测试用例使用不同的 @Before @After?

    我是新来的Java JUnit并遇到了不同的Fixtures 我在网上搜索了很多 但没有得到答案 是否可以使用不同的 Before After对于不同的测试用例JUnit 例如 我有以下 TC 那么是否可以使用不同的 Before用于测试和
  • 如何测试 JUnit 测试的 Comparator?

    我需要测试 Compare 方法 但我对如何测试感到困惑 我可以看看该怎么做吗 public class MemberComparator implements Comparator
  • 将 SoapUI 与 JUnit 集成

    我正在尝试将 SoapUI 集成到我预先存在的 JUnit 测试中 我在 SoapUI 3 6 1 中创建了一个测试 有用 我的下一步是将其应用到我的开发环境中 在我的 Eclipse 项目中 我已将 jar 添加到我的类路径中 我还创建了
  • 有 JUnit Attachments Jenkins 插件工作的示例吗?

    在过去一个小时左右的时间里 我一直在努力让以下工作正常进行 我将附件存储在目标目录中 但它们在班级级别或测试级别的测试页面上都没有链接 我尝试了以下每种组合 放置附件文件夹target surefire reports class 与目标
  • 为本地@ExceptionHandler编写JUnit测试

    我有以下控制器 class Controller ResponseStatus HttpStatus OK RequestMapping value verifyCert method RequestMethod GET public vo

随机推荐

  • Python——tensorflow2.8猫狗识别

    很早就想做这个猫狗识别的程序 所以跟着唐宇迪教程做了一遍 中间部分参数做了修改 后面预测部分用自己的猫猫图片做了预测 虽然有点问题 但最后还是可以识别出来 问题不大 下面对程序几个部分进行讲解 最后会附上整个程序的附件 一 数据处理 整个训
  • 三步使用bert搭建文本分类器

    不说废话 直接三步搭建最简单的bert文本多标签分类器 1 去官网https github com google research bert 下载一个bert模型 2 搭建bert service https github com hanx
  • 哈希学习简介

    一 背景介绍 1 首先介绍一下最近邻搜索 最近邻搜索问题 也叫相似性搜索 近似搜索 是从给定数据库中找到里查询点最近的点集的问题 给定一个点集 以及一个查询点q 需要找到离q最近的点的集合 在大规模高维度空间的情况下 这个问题就变得非常难
  • android 进程监控 top

    adb shell top h top h Usage top m max procs n iterations d delay s sort column t h m num Maximum number of processes to
  • mybatis-plus自定义分页实现 (精)

    添加pom依赖
  • EVE-NG初始安装及配置_笔记

    1 安装VMware 2 导入EVE的ova镜像 3 初始化配置 ubantu server linux 设置root密码 域名 主机名 IP地址 root eve 123456 123456 主机名 域名 IP地址获取 DHCP STAT
  • mysql数据库管理-mysql分区表管理

    1 分区概述 无论是哪种 MySQL 分区类型 要么分区表上没有主键 唯一键 要么分区表的主键 唯一键都必须包含分区键 也就是说不能使用主键 唯一键字段之外的其他字段分区 例如 emp 表的主键为id字段 在尝试通过store id字段分区
  • React实现拖拽效果

    最近遇到一个拖拽的业务 那么我们需要了解一下拖拽的流程 让我们来实现这个组件吧 一 拖拽流程 编写项目之前我们先了解一下拖拽大致的流程 以及触发的事件 其实拖拽一共分为三个步骤 1 onmousedown 拖拽事件的最开始 在这个简单我们要
  • 发现一个xdotool,是个神器

    xdotool是linux下 类似 按键精灵 的工具 在一些自动测试时 经常用到 以上为xdotool正常使用 比如说 模拟击键a xdotool key a 模拟两个键alt tab xdotool key alt Tab 自动输入wor
  • SeaTunnel本地运行以及kafka发送到redis说明

    下载 Seatunnel2 3 1源码 Idea中的目录结构 编译 通过maven进行代码编译 编译命令 mvn clean package pl seatunnel dist am Dmaven test skip true 编译单个模块
  • 【恶意代码与软件安全分析】(三)dynamic analysis

    恶意代码与软件安全分析 三 virtualbox崩掉了 只能跳过第二章先做第三章了 动态分析 在一个安全的环境下运行恶意软件并观察其行为 分析后输出内容 process Service Behavior 进程创建 进程终止 进程数 netw
  • Vue再学习2_组件开发

    Vue再学习2 组件开发 全局组件 在main js中配置 配置完成之后可以全局使用 1 引入组件对象 import GlobalTitle from components GlobalTitle vue 2 声明全局组件 Vue comp
  • cmd 执行html文件,cmd执行bat文件 cmd文件和bat文件有什么区别?

    cmd怎么执行dos下的bat文件在文件目录直接输入bt4 bat就可以了 记住要输入完整的文件名 包换后缀名 比如 11 bat在D盘根目录 在D gt 后面直接输入11 bat 回车 cmd下执行bat文件的命令 在cmd下执行bat文
  • idea 将springboot项目的Application加入service标签里

    idea 将springboot项目的Application启动器加入service标签里 最终效果图如下 第一步 最开始底部显示没有service服务 添加service 第三步 完成以上操作后底部会这样显示 然后点击 第四步 选择Mav
  • SQL Server [使用SSMS来分离数据库] 奋斗的珂珂~

    分离数据库 分离数据库就是将某个数据库 如student Mis 从SQL Server数据库列表中删除 使其不再被SQL Server管理和使用 但该数据库的文件 MDF 和对应的日志文件 LDF 完好无损 分离成功后 我们就可以把该数据
  • Android中的ConstraintLayout约束布局

    ConstraintLayout约束布局 ConstraintLayout有啥好处呢 可以减少布局层次 特别适合复杂的大型布局 可谓是集线性布局和相对布局于一身的荣誉布局 使用 添加依赖 目前 AndroidStudio新的版本默认就给你上
  • MMdetection3D学习系列(二)——KITTI数据集训练测试及可视化

    安装完环境以后 就可以进行测试了 这里我使用的是KITTI数据集进行测试 关于KITTI数据集 网上有很多介绍了 这里简单说一下在mmdet3d中它需要的文件层级样式吧 主要是针对RGB和点云数据进行检测 一般来说采用其中一侧的彩色摄像头的
  • centos7重启或关机卡死

    这个问题其实是systemd219这个版本的问题 查看systemd版本 请使用systemctl version 由于systemd进程的判断比之前更加严格 如果某些进程不响应SIGTERM信号 可能会导致重启是挂死 该问题和业务进程对S
  • Ubuntu查看安装的软件、.开头的文件

    1 dpkg l grep 比如 dpkg l grep libjansson4 2 show hidden files那里
  • Spring整合mybatis和Junit单元测试

    1 Spring整合mybatis 前提了解 spring 管理 mybatis mybatis 管理 mapper 要依赖于德鲁伊连接池 spring 管理sqlsessionfactory 思路 Spring整合Mybatis主要做两件