MyBatis with Spring – MyBatis与Spring

最后修改: 2019年 8月 14日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

MyBatis is one of the most commonly used open-source frameworks for implementing SQL databases access in Java applications.

MyBatis是最常用的开源框架之一,用于在Java应用程序中实现SQL数据库访问。

In this quick tutorial, we’ll present how to integrate MyBatis with Spring and Spring Boot.

在这个快速教程中,我们将介绍如何将MyBatis与Spring和Spring Boot集成。

For those not yet familiar with this framework, be sure to check out our article on working with MyBatis.

对于那些还不熟悉这个框架的人,请务必查看我们的关于使用MyBatis的文章

2. Defining the Model

2.定义模型

Let’s start by defining simple POJO that we’ll use throughout our article:

让我们从定义简单的POJO开始,我们将在整个文章中使用它。

public class Article {
    private Long id;
    private String title;
    private String author;

    // constructor, standard getters and setters
}

And an equivalent SQL schema.sql file:

还有一个相当的SQLschema.sql文件。

CREATE TABLE IF NOT EXISTS `ARTICLES`(
    `id`          INTEGER PRIMARY KEY,
    `title`       VARCHAR(100) NOT NULL,
    `author`      VARCHAR(100) NOT NULL
);

Next, let’s create a data.sql file, which simply inserts one record into our articles table:

接下来,让我们创建一个data.sql文件,它只是向我们的articles表插入一条记录。

INSERT INTO ARTICLES
VALUES (1, 'Working with MyBatis in Spring', 'Baeldung');

Both SQL files must be included in the classpath.

这两个SQL文件必须包含在classpath中。

3. Spring Config

3.Spring配置

To start using MyBatis, we have to include two main dependencies — MyBatis and MyBatis-Spring:

要开始使用MyBatis,我们必须包括两个主要的依赖项 – MyBatisMyBatis-Spring

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

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.2</version>
</dependency>

Apart from that, we’ll need basic Spring dependencies:

除此以外,我们还需要基本的Spring依赖性

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.8</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>5.3.8</version>
</dependency>

In our examples, we’ll use the H2 embedded database to simplify the setup and EmbeddedDatabaseBuilder class from the spring-jdbc module for configuration:

在我们的例子中,我们将使用H2嵌入式数据库来简化设置,并使用spring-jdbc模块中的EmbeddedDatabaseBuilder类进行配置。

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.199</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.8</version>
</dependency>

3.1. Annotation Based Configuration

3.1.基于注释的配置

Spring simplifies the configuration for MyBatis. The only required elements are javax.sql.Datasource, org.apache.ibatis.session.SqlSessionFactory, and at least one mapper.

Spring简化了MyBatis的配置。唯一需要的元素是javax.sql.Datasourceorg.apache.ibatis.session.SqlSessionFactory,以及至少一个映射器。

First, let’s create a configuration class:

首先,让我们创建一个配置类。

@Configuration
@MapperScan("com.baeldung.mybatis")
public class PersistenceConfig {

    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
          .setType(EmbeddedDatabaseType.H2)
          .addScript("schema.sql")
          .addScript("data.sql")
          .build();
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        return factoryBean.getObject();
    }
}

We also applied a @MapperScan annotation from MyBatis-Spring that scans defined packages and automatically picks up interfaces using any of the mapper annotations, such as @Select or @Delete.

我们还应用了MyBatis-Spring的@MapperScan注解,该注解扫描已定义的包,并自动拾取使用任何映射器注解的接口,例如@Select@Delete.

Using @MapperScan also ensures that every provided mapper is automatically registered as a Bean and can be later used with the @Autowired annotation.

使用@MapperScan还可以确保每个提供的映射器被自动注册为Bean,并且以后可以与@Autowired注解一起使用。

We can now create a simple ArticleMapper interface:

我们现在可以创建一个简单的ArticleMapper接口。

public interface ArticleMapper {
    @Select("SELECT * FROM ARTICLES WHERE id = #{id}")
    Article getArticle(@Param("id") Long id);
}

And finally, test our setup:

最后,测试我们的设置。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = PersistenceConfig.class)
public class ArticleMapperIntegrationTest {

    @Autowired
    ArticleMapper articleMapper;

    @Test
    public void whenRecordsInDatabase_shouldReturnArticleWithGivenId() {
        Article article = articleMapper.getArticle(1L);

        assertThat(article).isNotNull();
        assertThat(article.getId()).isEqualTo(1L);
        assertThat(article.getAuthor()).isEqualTo("Baeldung");
        assertThat(article.getTitle()).isEqualTo("Working with MyBatis in Spring");
    }
}

In the above example, we’ve used MyBatis to retrieve the only record we inserted previously in our data.sql file.

在上面的例子中,我们已经使用MyBatis来检索我们之前在data.sql文件中插入的唯一记录。

3.2. XML Based Configuration

3.2.基于XML的配置

As previously described, to use MyBatis with Spring, we need Datasource, SqlSessionFactory, and at least one mapper.

如前所述,要将MyBatis与Spring一起使用,我们需要DatasourceSqlSessionFactory,以及至少一个映射器。

Let’s create the required bean definitions in the beans.xml configuration file:

让我们在beans.xml配置文件中创建必要的bean定义。

<jdbc:embedded-database id="dataSource" type="H2">
    <jdbc:script location="schema.sql"/>
    <jdbc:script location="data.sql"/>
</jdbc:embedded-database>
    
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
</bean>

<bean id="articleMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="com.baeldung.mybatis.ArticleMapper" />
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

In this example, we also used the custom XML schema provided by spring-jdbc to configure our H2 datasource.

在这个例子中,我们还使用了由spring-jdbc提供的自定义XML模式来配置我们的H2数据源。

To test this configuration, we can reuse the previously implemented test class. However, we have to adjust the context configuration, which we can do by applying the annotation:

为了测试这个配置,我们可以重新使用之前实现的测试类。然而,我们必须调整上下文配置,我们可以通过应用注解来做到这一点。

@ContextConfiguration(locations = "classpath:/beans.xml")

4. Spring Boot

4.Spring Boot

Spring Boot provides mechanisms that simplify the configuration of MyBatis with Spring even more.

Spring Boot提供了一些机制,更加简化了MyBatis与Spring的配置。

First, let’s add the mybatis-spring-boot-starter dependency to our pom.xml:

首先,让我们把mybatis-spring-boot-starter依赖添加到我们的pom.xml

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

By default, if we use an auto-configuration feature, Spring Boot detects the H2 dependency from our classpath and configures both Datasource and SqlSessionFactory for us. In addition, it also executes both schema.sql and data.sql on startup.

默认情况下,如果我们使用自动配置功能,Spring Boot会从我们的classpath中检测到H2依赖,并为我们配置DatasourceSqlSessionFactory此外,它还在启动时执行schema.sqldata.sql

If we don’t use an embedded database, we can use configuration via an application.yml or application.properties file or define a Datasource bean pointing to our database.

如果我们不使用嵌入式数据库,我们可以通过application.ymlapplication.properties文件使用配置,或者定义一个Datasourcebean,指向我们的数据库。

The only thing we have left to do is to define a mapper interface, in the same manner as before, and annotate it with the @Mapper annotation from MyBatis. As a result, Spring Boot scans our project, looking for that annotation, and registers our mappers as beans.

我们唯一要做的就是以与之前相同的方式定义一个映射器接口,并用MyBatis的@Mapper注解对其进行注释。结果,Spring Boot扫描了我们的项目,寻找该注释,并将我们的映射器注册为Bean。

After that, we can test our configuration using the previously defined test class by applying annotations from spring-boot-starter-test:

之后,我们可以通过应用spring-boot-starter-test的注释,使用先前定义的测试类来测试我们的配置。

@RunWith(SpringRunner.class)
@SpringBootTest

5. Conclusion

5.结论

In this article, we explored multiple ways of configuring MyBatis with Spring.

在这篇文章中,我们探讨了用Spring配置MyBatis的多种方法。

We looked at examples of using annotation-based and XML configuration and showed the auto-configuration features of MyBatis with Spring Boot.

我们看了使用基于注解和XML配置的例子,并展示了MyBatis与Spring Boot的自动配置功能。

As always, the complete code used in this article is available over on GitHub.

一如既往,本文中使用的完整代码可在GitHub上找到。