Spring integrates Mybatis&Junit unit test

insert image description here
[Spring Technology] Spring Architecture
[Spring Technology] Spring IOC and DI Entry Case
[Spring Technology] Spring Bean Configuration and Examples
[Spring Technology] Spring Dependency Injection (DI Configuration)
[Spring Technology] Spring Third-Party Resource Configuration Management
[Spring Technology] Spring Container Technology
[Spring Technology] Spring Annotation Development
[Spring Technology] Spring Integration Mybatis&Junit Unit Test
[Spring Technology] Spring AOP
[Spring Technology] Spring Transaction Management

1. Spring integrates Mybatis [key]

1.1 Thought Analysis

problem import

Who is the core object of mybatis for data layer operations?

1.1.1 MyBatis program core object analysis

image-20210730114303147

1.1.2 Integrate MyBatis
  • Use SqlSessionFactoryBean to encapsulate the environment information required by SqlSessionFactory

image-20210730114342060

  • Use MapperScannerConfigurer to load the Dao interface, create a proxy object and save it in the IOC container

image-20210730114356175

1.2 Code implementation

problem import

Question 1: What is the dependency of Spring integrating mybatis?

Question 2: Which two beans need to be managed and configured by Spring to integrate mybatis, and what are the functions of these two beans?

【Pre-work】
  1. Add spring-context, druid, mybatis, mysql-connector-java and other basic dependencies in pom.xml.
  2. Prepare the service and dao layer basic code
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);
}
[Step 1] Import Spring to integrate Mybatis dependencies
<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>
[Step 2] Create JdbcConfig to configure DataSource data source
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;
    }
}
[Step 3] Create MybatisConfig to integrate 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;
    }
}
[Step 4] Create a SpringConfig main configuration class for package scanning and loading other configuration classes
@Configuration
@ComponentScan("com.itheima")
//@PropertySource:加载类路径jdbc.properties文件
@PropertySource("classpath:jdbc.properties")
@Import({
    
    JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {
    
    
}
[Step 5] Define the test class for testing
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 integrates Junit unit testing [key]

problem import

What are the two annotation functions of Spring integrating Junit?

[Step 1] Import the integrated dependency coordinate 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>

[Step 2] Use Spring to integrate Junit-specific class loaders

[Step 3] Load the configuration file or configuration class

//【第二步】使用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());
    }
}

Note: The dependency of junit must be at least version 4.12, it can be version 4.13, otherwise the following exception will occur:

image-20200831155517797

Guess you like

Origin blog.csdn.net/qq_51808107/article/details/130324719