SpringBoot 2.X Integration Mybatis

Posted by mecha_godzilla on Wed, 08 Jan 2020 00:52:23 +0100

1. Create a project environment

Check Web, Mybatis, MySQL as follows

Depends on the following

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

After creation, note that MyBatis relies on a different naming than other libraries. Yes, this integrated jar package is not springboot's own, which means that the starter is provided by a third party, just like a Druid data source, and is also a third party.

For easy reading, first post the class location information written by the following operation, as shown below:

2. Configure database connection information

Use yml here

spring:
  datasource:
    username: root
    url: jdbc:mysql://localhost:3306/ufida?serverTimezone=UTC
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
#If you want to use a Druid data source, you need to import the corresponding jar package, or you can specify no type
    type: com.alibaba.druid.pool.DruidDataSource

Once configured, MyBatis can create entity classes to use.

3. Write entity classes

Entity class: Userdao under dao package

public class Userdao {
    private int user_id;
    private String userName;
    private String passWord;
    private int usertypeid;

    getXXX...
    setXXX...
    toString...
}

4. Write Mapper interface class

Mapper interface class: UserMapper under mapper package

@Mapper
@Repository   
public interface UserMapper {
   //It's just an integration test, there's only one method written for readability
    List<Userdao> queryUserList();
}

Note here that the @Mapper annotation adds a location on the interface class that generates the corresponding interface implementation class after compilation, which is also officially recommended!This is just testing and integrating mybatis to write a Mapper interface. If there is a need for many interfaces to become implementation classes, you need to add the @Mapper annotation on each interface class, which is more cumbersome, to solve this problem, use the @MapperScan annotation.Simply put, @MapperScan annotation is equivalent to scanning the specified package directly. The code above is in the package com.yichunnnn.jdbcboot.mapper. If you want to annotate with @MapperScan, you can do the following

@MapperScan("com.yichunnnn.jdbcboot.mapper")  //Equivalent to @Mapper
@SpringBootApplication
public class JdbcbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(JdbcbootApplication.class, args);
    }
}

5. Write Mapper Mapping File

The location and name of the Mapper mapping file is: classpath:mybatis/mapper/UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.yichunnnn.jdbcboot.mapper.UserMapper">

    <select id="queryUserList" resultType="Userdao">
        select * from user
    </select>
</mapper>

For readability, write only one query method here, with special attention

Every mistake will go wrong!

6. SpringBoot Integration Mybatis

In fact, the integration of Mybatis is like our programmer's lifetime.

Before SpringBoot integrated Mybatis, we recalled that when MyBatis was used alone, the myBatis core profile had to configure data sources, transactions, connection database accounts, passwords, and so on. It was all this stuff, all in person.This is our trough

When myBatis integrates with Spring, configuring data sources, transactions, accounts connecting to databases, and anything else is managed by Spring; you don't have to manage anything yourself.This is when we are proud of the spring, our career has come to an end.

Later, when springboot integrates Mybatis, springboot is ready by default for whatever data source it is, even if it doesn't use the mybatis configuration file. If we have already written our own mapping configuration file for myBatis, just tell springboot where these files are located, as follows (yml notation). It's a career success, marrying White Rich.To the top of life...

#integration Mybatis   #Specify the core configuration file and Mapper mapping file for myBatis
mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml
#Note: Path to corresponding entity class
  type-aliases-package: com.yichunnnn.jdbcboot.dao


Stories are beautiful, but facts are bony...

The final configuration file is also shown in the illustration above. If you need to fully understand the configuration file, you can view it from the org.mybatis.spring.boot.autoconfigure.MybatisProperties class (you can access it by clicking on the properties of the mouse) or, of course, from the official documentation: http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

7. Write controller layer code

@RestController
public class MybatisController {
    @Autowired
    private UserMapper userMapper;

    @GetMapping("/selectUser")
    public String selectUser(){
        List<Userdao> userdaos = userMapper.queryUserList();
        for (Userdao user : userdaos) {
            System.out.println(user);
        }
        return "select success == SpringBoot 2.X integration Mybatis Success!";
    }
}

Run tests

If the effect is above, the integration is successful!

8. SpringBoot 2.X Integrate Mybatis Principle

The SpringBoot 2.X Integration Mybatis principle is actually implied in the org.mybatis.spring.boot.autoconfigure package, which contains the essence of the SpringBoot Integration Mybatis principle, as follows

When myBatis integrates with spring, developers need to provide themselves with two beans, a SqlSessionFactory Bean and a MapperScannerConfigurer, which in Spring Boot, do not mean that the two beans are no longer needed, in the org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration class,We can see that Spring Boot provides both beans, and the key sources are as follows:

@org.springframework.context.annotation.Configuration
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties(MybatisProperties.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MybatisAutoConfiguration implements InitializingBean {

  @Bean
  @ConditionalOnMissingBean
  public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
    SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
    factory.setDataSource(dataSource);
    return factory.getObject();
  }
  @Bean
  @ConditionalOnMissingBean
  public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    ExecutorType executorType = this.properties.getExecutorType();
    if (executorType != null) {
      return new SqlSessionTemplate(sqlSessionFactory, executorType);
    } else {
      return new SqlSessionTemplate(sqlSessionFactory);
    }
  }
  @org.springframework.context.annotation.Configuration
  @Import({ AutoConfiguredMapperScannerRegistrar.class })
  @ConditionalOnMissingBean(MapperFactoryBean.class)
  public static class MapperScannerRegistrarNotFoundConfiguration implements InitializingBean {

    @Override
    public void afterPropertiesSet() {
      logger.debug("No {} found.", MapperFactoryBean.class.getName());
    }
  }
}

The annotations on the class show that the configuration here takes effect when SqlSessionFactory, SqlSessionFactoryBean, and DataSource are present in the current class path, and both SqlSessionFactory and SqlTemplate are provided.The meaning of this code is that it serves as an important reference when configuring MyBatis multiple data sources in Spring Boot!

Of course, if you are interested in the configuration properties of mybatis, you can also refer to the MybatisProperties class. To explore more principles, focus on the org.mybatis.spring.boot.autoconfigure package!

If this article helps you a little, please give a compliment, thank you~

Finally, if there are any deficiencies or inaccuracies, you are welcome to correct the criticism and appreciate it!If in doubt, please leave a message and reply immediately!

Welcome to my Public Number, which contains some java learning materials and a large wave of Java e-books, such as Professor Zhou Zhiming's in-depth Java virtual machine, Java programming ideas, core technology volume, big story design mode, Java Concurrent Programming practice.....are all the Bibles of java, let's not say get on the Tomcat car, let's go!The most important thing is to explore technology together, yearn for technology, and pursue technology. Well, if you come, you'll be friends.


Reference resources:
http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

https://blog.csdn.net/u012702547/article/details/88643598

Topics: Java Mybatis Spring SpringBoot