Spring整合Mybatis&Junit单元测试

简介: Spring整合Mybatis&Junit单元测试

1. Spring整合Mybatis【重点】


1.1 思路分析


问题导入

mybatis进行数据层操作的核心对象是谁?


1.1.1 MyBatis程序核心对象分析


dc9174ca01503117c135776ed1e11c6a_20f7433530bcb4bf782679e1a38752ff.png


1.1.2 整合MyBatis


使用SqlSessionFactoryBean封装SqlSessionFactory需要的环境信息


e2633f0c6c0318a11460a3914cbf2044_fe992df895e05eddb681f6feabb5ebef.png


使用MapperScannerConfigurer加载Dao接口,创建代理对象保存到IOC容器中


b697627f3e36c1ceba3f7cfd65fd0185_d67164c9099e3adadae8b55a5a0d9b8a.png


1.2 代码实现


问题导入


问题1:Spring整合mybatis的依赖叫什么?


问题2:Spring整合mybatis需要管理配置哪两个Bean,这两个Bean作用分别是什么?


【前置工作】


在pom.xml中添加spring-context、druid、mybatis、mysql-connector-java等基础依赖。

准备service和dao层基础代码


public interface AccountService {
    void save(Account account);
    void delete(Integer id);
    void update(Account account);
    List<Account> findAll();
    Account findById(Integer id);
}
@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();
    }
}
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);
}



【第一步】导入Spring整合Mybatis依赖


<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.10.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.0</version>
</dependency>


【第二步】创建JdbcConfig配置DataSource数据源


jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false
jdbc.username=root
jdbc.password=root


public class JdbcConfig {
    @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
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(userName);
        ds.setPassword(password);
        return ds;
    }
}



【第三步】创建MybatisConfig整合mybatis


public class MybatisConfig {
    //定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setTypeAliasesPackage("com.itheima.domain");
        ssfb.setDataSource(dataSource);
        return ssfb;
    }
    //定义bean,返回MapperScannerConfigurer对象
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.itheima.dao");
        return msc;
    }
}



【第四步】创建SpringConfig主配置类进行包扫描和加载其他配置类


@Configuration
@ComponentScan("com.itheima")
//@PropertySource:加载类路径jdbc.properties文件
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {
}


【第五步】定义测试类进行测试


public class App {
    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        AccountService accountService = ctx.getBean(AccountService.class);
        Account ac = accountService.findById(1);
        System.out.println(ac);
    }
}


2. Spring整合Junit单元测试【重点】


问题导入


Spring整合Junit的两个注解作用分别是什么?


【第一步】导入整合的依赖坐标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>


【第二步】使用Spring整合Junit专用的类加载器

【第三步】加载配置文件或者配置类


//【第二步】使用Spring整合Junit专用的类加载器
@RunWith(SpringJUnit4ClassRunner.class)
//【第三步】加载配置文件或者配置类
@ContextConfiguration(classes = {SpringConfiguration.class}) //加载配置类
//@ContextConfiguration(locations={"classpath:applicationContext.xml"})//加载配置文件
public class AccountServiceTest {
    //支持自动装配注入bean
    @Autowired
    private AccountService accountService;
    @Test
    public void testFindById(){
        System.out.println(accountService.findById(1));
    }
    @Test
    public void testFindAll(){
        System.out.println(accountService.findAll());
    }
}


注意:junit的依赖至少要是4.12版本,可以是4.13等版本,否则出现如下异常:


317dc8ed952f3c738916dc3aaa9128e8_a90e584bec3645126a92f461689ee295.png


相关文章
|
4天前
|
XML Java 测试技术
Spring5入门到实战------17、Spring5新功能 --Nullable注解和函数式注册对象。整合JUnit5单元测试框架
这篇文章介绍了Spring5框架的三个新特性:支持@Nullable注解以明确方法返回、参数和属性值可以为空;引入函数式风格的GenericApplicationContext进行对象注册和管理;以及如何整合JUnit5进行单元测试,同时讨论了JUnit4与JUnit5的整合方法,并提出了关于配置文件加载的疑问。
Spring5入门到实战------17、Spring5新功能 --Nullable注解和函数式注册对象。整合JUnit5单元测试框架
|
4天前
|
SQL Java 数据库
2、Mybatis-Plus 测试增、删、改、查
这篇文章是关于使用Mybatis-Plus进行数据库的增删改查操作的本地测试,包括创建数据库表、添加数据、创建使用lombok的实体类、添加mapper接口以及编写测试代码进行基本的数据库操作验证。
2、Mybatis-Plus 测试增、删、改、查
|
4天前
|
前端开发 Java 测试技术
单元测试问题之在Spring MVC项目中添加JUnit的Maven依赖,如何操作
单元测试问题之在Spring MVC项目中添加JUnit的Maven依赖,如何操作
|
17天前
|
Java 测试技术 API
深入理解单元测试:JUnit框架在Java中的应用
【8月更文挑战第3天】本文将引导读者通过JUnit框架的镜头,探索单元测试的奥秘。我们将一起揭开单元测试的神秘面纱,了解其在软件开发中的关键作用,并具体学习如何在Java项目中应用JUnit进行有效的单元测试。文章不仅会涉及理论概念,还将通过具体的代码示例,展示如何编写和运行单元测试,以确保软件质量。让我们开始吧,一起踏上这段提升代码质量和开发效率的旅程。
14 0
|
1月前
|
Java 测试技术 开发工具
使用Spring Boot和Spock进行单元测试
使用Spring Boot和Spock进行单元测试
|
1月前
|
IDE Java 测试技术
Java面试题:描述在Java中使用JUnit进行单元测试的过程
Java面试题:描述在Java中使用JUnit进行单元测试的过程
22 0
|
1月前
|
Java 测试技术 数据库
在Spring Boot项目中集成单元测试的策略
在Spring Boot项目中集成单元测试的策略
|
2月前
|
缓存 Java 测试技术
Spring Boot中的性能测试与调优
Spring Boot中的性能测试与调优
|
3月前
|
Java 测试技术 Spring
Spring Boot 基于 JUnit 5 实现单元测试
Spring Boot 基于 JUnit 5 实现单元测试
97 0
|
3月前
|
Java 测试技术 Maven
Spring整合JUnit实现单元测试
本文介绍了如何在Java开发中使用Spring与JUnit进行单元测试。首先,设置JUnit和Spring环境,创建待测试的业务逻辑类,如MyService。接着,编写JUnit测试类MyServiceTest,使用`@RunWith(SpringJUnit4ClassRunner.class)`和`@ContextConfiguration`注解,注入并测试MyService的方法。此外,借助Mockito模拟依赖对象,以及使用Spring TestContext框架进行集成测试,确保测试的隔离性和环境的稳定性。通过这些方法,可以提升代码质量和测试效率。
43 1