1. 簡介
MyBatis 是在 Java 應用中實現 SQL 數據庫訪問最常用的開源框架之一。
在本快速教程中,我們將介紹如何將 MyBatis 與 Spring 和 Spring Boot 集成。
如果您還不熟悉該框架,請查看我們關於使用 MyBatis 的文章。
2. 定義模型
讓我們首先定義我們將會在本文中使用的簡單POJO:
public class Article {
private Long id;
private String title;
private String author;
// constructor, standard getters and setters
}<p>以及一個等效的 SQL <em>schema.sql</em> 文件:</p>
CREATE TABLE IF NOT EXISTS `ARTICLES`(
`id` INTEGER PRIMARY KEY,
`title` VARCHAR(100) NOT NULL,
`author` VARCHAR(100) NOT NULL
);接下來,我們創建一個名為 data.sql 的文件,其中包含一條記錄,插入到我們的 articles 表中:
INSERT INTO ARTICLES
VALUES (1, 'Working with MyBatis in Spring', 'Baeldung');必須將這兩個 SQL 文件包含在類路徑中。
3. Spring 配置
要開始使用 MyBatis,我們需要包含兩個主要依賴項:MyBatis 和 MyBatis-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>除此之外,我們還需要一些基本 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>在我們的示例中,我們將使用 H2嵌入式數據庫 以簡化設置,並使用 EmbeddedDatabaseBuilder 類來自 spring-jdbc 模塊進行配置。
<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 基於標註的配置
Spring 簡化了 MyBatis 的配置。唯一必需的元素是:<em >javax.sql.Datasource</em>、<em >org.apache.ibatis.session.SqlSessionFactory</em> 和至少一個映射器。
首先,讓我們創建一個配置類:
@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();
}
}我們還應用了 MyBatis-Spring 中的 @MapperScan 註解,該註解掃描定義的包並自動拾取使用任何 mapper 註解(如 @Select 或 @Delete)的接口。
使用 @MapperScan 還可以確保所有提供的 mapper 接口自動註冊為 Bean,並且可以使用 @Autowired 註解進行注入。
現在,我們可以創建一個簡單的 ArticleMapper 接口:
public interface ArticleMapper {
@Select("SELECT * FROM ARTICLES WHERE id = #{id}")
Article getArticle(@Param("id") Long id);
}<p>最後,測試我們的配置。</p>
@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");
}
}在上面的示例中,我們使用了 MyBatis 來檢索我們之前在 data.sql文件中插入的唯一記錄。
3.2. 基於 XML 的配置
如前所述,要使用 MyBatis 與 Spring 結合,我們需要 數據源、SqlSessionFactory 至少一個映射器。
讓我們在 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>在此示例中,我們還使用了 spring-jdbc 提供的自定義 XML 模式來配置我們的 H2 數據源。
為了測試此配置,我們可以重用先前實現的測試類。但是,我們需要調整上下文配置,可以通過應用註解來實現。
@ContextConfiguration(locations = "classpath:/beans.xml")4. Spring Boot
Spring Boot 提供機制,進一步簡化了 MyBatis 與 Spring 的配置。
首先,讓我們添加 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>默認情況下,如果使用自動配置功能,Spring Boot 會檢測classpath中 H2 依賴項,並自動配置 Datasource 和 SqlSessionFactory。 此外,它還會啓動時執行 schema.sql 和 data.sql。
如果未使用嵌入式數據庫,我們可以通過 application.yml 或 application.properties 文件進行配置,或者定義一個 Datasource Bean 指向我們的數據庫。
剩下的只是定義一個 Mapper 接口,就像之前一樣,並使用 MyBatis 的 @Mapper 註解進行標註。 這樣,Spring Boot 會掃描項目,查找該註解,並註冊我們的 Mapper 作為 Bean。
之後,我們可以使用之前定義的測試類,並應用 spring-boot-starter-test 中的註解來測試我們的配置:
@RunWith(SpringRunner.class)
@SpringBootTest5. 結論
在本文中,我們探討了多種配置 MyBatis 與 Spring 的方法。
我們考察了使用註解式和 XML 配置的示例,並展示了 MyBatis 與 Spring Boot 的自動配置功能。