Integrating Mybatis for SpringBoot data access

This is the 8th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Environment construction and pre-knowledge review

There are two forms of start in SpringBoot:

  1. Official: spring – the boot – starter – *
  2. Third party: *-spring-boot-starter

Mybatis belongs to the third party, so we need to find its official website, configuration documents, etc.

Intimate link: Github

Remember to switch tags when you enter

The author uses the latest version 2.2.0;

Find the pom.xml below it, and you can get:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>
Copy the code

At the bottom of the page, find the Quick Start document:

Mybatis (mybatis)

  1. Import myBatis dependencies and database drivers
  2. Connecting to the database
  3. Add global config file (mybatis-config.xml)
  4. Write the utility class: SqlSessionFactory
  5. The use of sqlSession
  6. Write the Mapper
  7. .

Druid configuration: Druid

Analyze Mybatis initiator automatic configuration

Find MybatisAutoConfiguration,

@ConditionalOnSingleCandidate(DataSource.class)
Copy the code

Only one data source is allowed in the container.

@EnableConfigurationProperties(MybatisProperties.class)
Copy the code

@ EnableConfigurationProperties (class. The class)

  1. Example Enable the class binding function
  2. Automatically register the class and component in the container

Let’s go to myBatisproperty.class and see:

As we can see from the figure above, we only need to use mybatis as the preposition in the configuration file, and then we can use it.

With the configuration clear, let’s take a look at what the initiator autoinstalls for us:

  1. @Bean
    @ConditionalOnMissingBean 
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource)
    Copy the code

    Corresponding to step 4 of the previous usage process, it is now automatically configured

  2. @Bean
    @ConditionalOnMissingBean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory)
    Copy the code

    **SqlSessionTemplate **

  3. @ Import (AutoConfiguredMapperScannerRegistrar. Class), as long as we write operation MyBatis interface, marking the @ Mapper will be automatic scanning come in, the use of the corresponding before process step 6.

Integration of Mybatis

Official documentation for Mybatis

Directory structure:

First create a global configuration file (myBatis -config.xml) :


      
<! DOCTYPEconfiguration
        PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

</configuration>
Copy the code

The Configuration consists of a DataSource that obtains the database connection instance and a TransactionManager that determines the scope and control mode of the transaction. Since our data source has already been configured via Druid, just clean it up.

Entity class

Create an entity class as consistent as possible with the database field name.

import lombok.Data;

@Data
public class User {
    private int id;
    private String username;
    private String password;
}
Copy the code

Mapper layer (compared with Dao)

Create the GetUserMapper interface.

import com.xbhog.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface GetUserMapper {
    public User getUserid(int id);
}

Copy the code

Implementation interface:

Create getUserMapper. XML, implement the interface or binding interface, write add, delete, change and check.


      
<! DOCTYPEmapper
        PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xbhog.Mapper.GetUserMapper">

    <select id="getUserid" resultType="com.xbhog.pojo.User">
        select * from user where id = #{id}
    </select>
</mapper>
Copy the code

Id corresponds to the abstract method getUserid in the GetUserMapper interface, and the return value type User corresponds to the result set type.

In fact, we can now create a controller to implement access, to facilitate the extension of the sequential function, we can create a service layer, as a saying, if there is a problem, it can not be solved by adding a layer, then add another layer.

Service layer: DemoService

import com.xbhog.Mapper.GetUserMapper;
import com.xbhog.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class DemoService {
    @Autowired
    GetUserMapper getUserMapper;

    public User getUser(int id){
        returngetUserMapper.getUserid(id); }}Copy the code

Get GetUserMapper out of the container and invoke it at the Service layer. If you are just testing, you can simply omit creating the Controller.

Create a Controller:

@Controller
public class Mycontro {
    @Autowired
    DemoService demoService;

    @ResponseBody
    @GetMapping("/user")
    public User getById(@RequestParam("id") int id){
        returndemoService.getUser(id); }}Copy the code

After the above steps are completed, you need to register in MyBatis and Springboot in the configuration file:

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml   Global configuration file location
  mapper-locations: classpath:mybatis/Mapper/*.xml # SQL maps file location
Copy the code

Full configuration:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/vuesite
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
    druid:
      aop-patterns: com.xbhog.*
      filters: stat,wall
      stat-view-servlet:
        enabled: true
        login-password: admin
        login-username: admin
        reset-enable: false


      web-stat-filter:
        enabled: true
        url-pattern: / *
        exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'

      filter:
        stat:
          slow-sql-millis: 1000
          log-slow-sql: true
          enabled: true
        wall:
          enabled: true
          config:
            drop-table-allow: false


mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/Mapper/*.xml
Copy the code

Testing:

Input: localhost: 8080 / user? Id =2 Query the user whose ID is 2

Results:

{"id":2."username":"demo"."password":"123456"}
Copy the code

If before a Druid configuration, can look at http://localhost:8080/druid/

Pay attention to the point

Hump name:

If the field in the database is Camel-Case, then we need to enable Camel-Case in mybatis, if not, the corresponding data cannot be found.

In the global configuration file:


      
<! DOCTYPEconfiguration
        PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>
Copy the code

Global configuration Settings:

In fact, myBatis -start in springBoot already has global configuration properties.

Find the MybatisProperties configuration properties class.

After entering the Configuration file, we find that the Configuration we need has been set in it. In the future, we only need to set the properties in the Configuration file:

So we can delete the global configuration file. Configure in yamL or Properties:

mybatis:
# config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/Mapper/*.xml
  configuration:  Global configuration file
    map-underscore-to-camel-case: true
Copy the code

Summarize the integration process of MyBatis:

  • Import myBatis official starter

  • Write the Mapper interface. Standard @mapper annotations

  • Write an SQL mapping file and bind the Mapper interface

  • Specify the location of the Mapper configuration file in application.yaml, and specify information about the global configuration file (recommended; Configuration in mybatis. The configuration)

The end:

If you see here or just to help you, I hope you can point to like, focus, collection, thank you;

If there are any errors, please point them out in the comments and the author sees them will be corrected.