[Spring] Spring整合MyBatis/Spring整合Junit单元测试

✨✨个人主页:沫洺的主页

 系列专栏:  JavaWeb专栏 JavaSE专栏  Java基础专栏vue3专栏 

                           MyBatis专栏Spring专栏SpringMVC专栏

如果文章对你有所帮助请留下三连✨✨

Spring整合MyBatis

环境搭建

使用到的相关依赖

    
      org.springframework
      spring-context
      5.2.10.RELEASE
    
    
      com.alibaba
      druid
      1.1.16
    
    
      mysql
      mysql-connector-java
      5.1.49
    
    
      org.mybatis
      mybatis
      3.5.9
    
    
      org.springframework
      spring-jdbc
      5.3.2
    
    
      org.mybatis
      mybatis-spring
      2.0.6
    
    
      org.projectlombok
      lombok
      1.18.24
      compile
    

数据库

[Spring] Spring整合MyBatis/Spring整合Junit单元测试_第1张图片

实体类(domain通常就代表了与数据库表一一对应的javaBean)

com/moming/domain/Account

[Spring] Spring整合MyBatis/Spring整合Junit单元测试_第2张图片

准备service和dao层基础代码

dao/AccountDao

package com.moming.dao;

import com.moming.domain.Account;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface AccountDao {

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

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

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

    @Select("select * from tb_money")
    List findAll();

    @Select("select * from tb_money where id = #{id} ")
    Account findById(Integer id);
}

service/AccountService

package com.moming.service;

import com.moming.domain.Account;

import java.util.List;

public interface AccountService {

    void save(Account account);

    void delete(Integer id);

    void update(Account account);

    List findAll();

    Account findById(Integer id);

}

service/impl/AccountServiceImpl

package com.moming.service.impl;

import com.moming.dao.AccountDao;
import com.moming.domain.Account;
import com.moming.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@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 findAll() {
        return accountDao.findAll();
    }
}

resources/jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///db5?useSSL=false&useServerPrepStmts=true
jdbc.username=root
jdbc.password=123456

普通使用mybatis方法

创建resources/mybatis.xml核心配置文件




    
    
    
    
        
    

    
        
            
            
                
                
                
                
            
        
    
    
        
        
    

创建SpringConfig主配置类进行包扫描

package com.moming.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.moming")
public class SpringConfig {
}

定义测试类App1进行测试

package com.moming;

import com.moming.dao.AccountDao;
import com.moming.domain.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class App1 {
    public static void main(String[] args) throws IOException {
        //加载mybatis的核心配置文件,获取SqlSessionFactory
        //定义配置文件的路径
        String resource = "mybatis.xml";
        //资源加载返回字节输入流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //获取工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //执行sql
        //参数就是sql语句的唯一标识
        //自动封装结果集
        //3.1使用代理接口,先拿对象,再调方法
        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
        Account byId = accountDao.findById(2);
        System.out.println(byId);
        //释放资源
        sqlSession.close();
    }
}

运行结果

[Spring] Spring整合MyBatis/Spring整合Junit单元测试_第3张图片

Spring整合MyBatis

首先要知道mybatis进行数据层操作的核心对象是SqlSessionFactory

[Spring] Spring整合MyBatis/Spring整合Junit单元测试_第4张图片

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

[Spring] Spring整合MyBatis/Spring整合Junit单元测试_第5张图片

 使用MapperScannerConfigurer加载Dao接口,创建代理对象保存到IOC容器中 [Spring] Spring整合MyBatis/Spring整合Junit单元测试_第6张图片

整合案例

创建JdbcConfig配置DataSource数据源

package com.moming.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

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;
    //1.定义一个方法获得要管理的对象
    //2.添加@Bean 表示当前方法的返回值是一个bena
    @Bean
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(userName);
        ds.setPassword(password);
        return ds;
    }
}

创建MybatisConfig整合mybatis

package com.moming.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

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

创建SpringConfig主配置类进行包扫描和加载其他配置类

package com.moming.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;

@Configuration
@ComponentScan("com.moming")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {
}

定义测试类App进行测试

package com.moming;

import com.moming.config.SpringConfig;
import com.moming.domain.Account;
import com.moming.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

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

运行成功

[Spring] Spring整合MyBatis/Spring整合Junit单元测试_第7张图片

Spring整合Junit单元测试 

导入整合的依赖坐标spring-test



  junit
  junit
  4.12



  org.springframework
  spring-test
  5.1.9.RELEASE

使用Spring整合Junit专用的类加载器

[Spring] Spring整合MyBatis/Spring整合Junit单元测试_第8张图片

 加载配置文件或者配置类

[Spring] Spring整合MyBatis/Spring整合Junit单元测试_第9张图片

 测试运行成功

[Spring] Spring整合MyBatis/Spring整合Junit单元测试_第10张图片

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

你可能感兴趣的:(Spring,MyBatis,mybatis,spring,java)