Mybatis – configuration and integration

Time:2021-11-29

preface

This article will discuss how to build aMybatisTest engineering is introduced and introduced on this basisSpringbootintegrationMybatis

text

1、 Mybatis project construction

1. Create a database and create a table

First create a file calledtestofMySQLDatabase, and intestCreate one in the databasebookTable. The table creation statement is as follows.

CREATE TABLE book(
    id INT(11) PRIMARY KEY AUTO_INCREMENT,
    b_name VARCHAR(255) NOT NULL,
    b_price FLOAT NOT NULL
)

Then gobookInsert three pieces of data into the table, and the insertion statement is as follows.

INSERT INTO book (b_name, b_price) VALUES ("Math", 20.5)
INSERT INTO book (b_name, b_price) VALUES ("English", 21.5)
INSERT INTO book (b_name, b_price) VALUES ("Water Margin", 30.5)

The above data is used forMybatisAfter the project is built, whether the test can be based onMybatisOperate on the data in the database.

2. Add dependency

Need inPOMAdd to fileMybatisAnd database driven dependencies.POMThe dependencies added to the file are as follows.

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.6</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.16</version>
</dependency>

In introductionMySQLWhen using the database driver, you should pay attention to the installationMySQLThe database version should match the driver version. See the following table for the specific relationship.

Connector/J Version Driver Type JDBC Version MySQL Server Version state
5.1 4 3.0,4.0,4.1,4.2 5.6,5.7,8.0 available
8.0 4 4.2 5.6,5.7,8.0 Recommended use

Due to installedMySQLThe database version is 8.0.26, so according to the official recommendation, the driver version used is 8.0.16, while the driver version of 8.0 isMySQLDatabase driver in configurationdataSourceWhen,driverProperty needs to be set tocom.mysql.cj.jdbc.Driver, different from 5.1com.mysql.jdbc.Driver

3. Configuration file

Add goodMybatisAfter related dependencies, you need to writeMybatisConfiguration file formybatis-config.xml, as shown below.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="useGeneratedKeys" value="true"/>
    </settings>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&amp;serverTimezone=UTC&amp;useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <package name="com.mybatis.learn.dao"/>
    </mappers>
</configuration>

If you don’t know the labels and meanings of the configuration file, you can refer to the mybatis XML configuration, which contains information aboutMybatisDetailed description of the configuration.

4. Entity class

Create a newBookEntity classes for andbookTable, as shown below.

@Data
public class Book {

    private long id;
    private String bookName;
    private float bookPrice;

}

5. Mapping interface and mapping file

Because inmybatis-config.xmlWhen registering a mapping file in, it is based on<package name="com.mybatis.learn.dao"/>This method requires that the mapping interface and the mapping file must have the same name and in the same directory, so a mapping interface namedBookMapperAnd write a mapping file namedBookMapper.xml。 Mapping interfaceBookMapperAs shown below.

public interface BookMapper {

    List<Book> selectAllBooks();

}

Mapping fileBookMapper.xmlAs shown below.

<?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.mybatis.learn.dao.BookMapper">
    <resultMap id="bookResultMap" type="com.mybatis.learn.entity.Book">
        <result column="b_name" property="bookName"/>
        <result column="b_price" property="bookPrice"/>
    </resultMap>
    
    <select id="selectAllBooks" resultMap="bookResultMap">
        SELECT
        b.id, b.b_name, b.b_price
        FROM
        book b
    </select>
</mapper>

becausemavenBy default, thesrc/main/javaLower nonJavaFiles are packaged, so you need toPOMThe following configuration is made in the file to package the mapping file.

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>

6. Engineering structure

The whole project structure is as follows.

Mybatis - configuration and integration

amongMybatisTestClass is used to test the query function, as shown below.

public class MybatisTest {

    public static void main(String[] args) throws Exception {
        String resource = "mybatis-config.xml";
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(Resources.getResourceAsStream(resource));
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
        List<Book> books = bookMapper.selectAllBooks();
        books.forEach(book -> System.out.println(book.toString()));
    }

}

Pay special attention hereResources.getResourceAsStream()For this method, the comments of this method are as follows.

Returns a resource on the classpath as a Stream object.

NamelyResources.getResourceAsStream()This method will loadclasspathUnder the configuration file, then inMybatisTestIn the test class, you will goclasspathThe next load name ismybatis-config.xmlConfiguration file for. Now compile the whole project and check the compiled directory structure, as shown below.

Mybatis - configuration and integration

So it can be read successfullyMybatisConfiguration file for.

Execute nowMybatisTestTest class, the results are as follows.

Mybatis - configuration and integration

The above results show that the whole test project is built successfully and can be passedMybatisOperate on the database.

2、 Spring boot integrates mybatis

MybatisProvides andSpringbootIntegrated initiator, based on initiator, can be used convenientlyMybatis, this section willSpringbootintegrationMybatisIntroduce.

First inPOMImport from fileMybatisStarter, as shown below.

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>

The final test is based onrestThe tool calls the interface to trigger the operation on the database, so it also needs to be introducedwebDependency, as shown below.

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

In usemybatis-spring-boot-starterAfter the starter, it is no longer necessary toMybatisProvide a configuration file forMybatisThe configuration of is written directly in theapplication.ymlIf inapplication.ymlThere are no pairs in theMybatisAny configuration, thenMybatisAll configuration items will use default values. meanwhiledataSourceThe configuration of is no longer configured toMybatisIn accordance withSpringbootYou can configure the data source by configuring it.application.ymlThe contents of the file are as follows.

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
    username: root
    password: root

mybatis:
  configuration:
    use-generated-keys: true

In this section, map interfacesBookMapper, mapping fileBookMapper.xmlAnd entity classesBookIt is completely consistent with the first section, so it will not be repeated here, but it needs to beSpringbootStart class plus@MapperScanAnnotation to specify the directory where the mapping file is located, as shown below.

@SpringBootApplication
@MapperScan("com.mybatis.learn.dao")
public class MybatisLearnApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisLearnApplication.class, args);
    }

}

So far, the integration has been completed, and the whole project structure is as follows.

Mybatis - configuration and integration

serviceLayer andcontrollerLayers are used for testing.MybatisServiceThe implementation of is as follows.

@Service
public class MybatisService {

    @Autowired
    private BookMapper bookMapper;

    public List<Book> selectAllBooks() {
        return bookMapper.selectAllBooks();
    }

}

After successful consolidation, you canSpringGet the mapping instance of each mapping interface in the container, soMybatisServiceThe mapping interface is obtained by injectionBookMapperMapping instance for.MybatisControllerThe implementation of is as follows.

@RestController
public class MybatisController {

    @Autowired
    private MybatisService mybatisService;

    @RequestMapping(value = "/api/v1/selectall", method = RequestMethod.GET)
    public ResponseEntity<List<Book>> selectAllBooks() {
        List<Book> books;
        try {
            books = mybatisService.selectAllBooks();
        } catch (Exception e) {
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<>(books, HttpStatus.OK);
    }

}

Finally based onrestThe tool calls the interface, and the results are as follows.

Mybatis - configuration and integration

summary

This article describes how toMavenBy introducingMybatisRely on the package to build a test project to connect to the database, and thenSpringbootintegrationMybatisA case demonstration is carried out, either way, throughMybatisOperating databases are compared with traditional databasesJDBCThe method has more convenient and powerful characteristics.