使用 Spring Boot 和 Maven 的 Hello world

  1. 將必要的依賴項新增到專案 POM(mybatismybatis-spring):
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>x.x.x</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.1-SNAPSHOT</version>
</dependency>

建立 mybatis 會話需要 SqlSessionFactory。Spring 允許使用 SqlSessionFactoryBean 快速配置。只需定義一個 SqlSessionFactoryBean bean,並提供對 DataSource bean 的引用:

@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSource);
    return sqlSessionFactoryBean;
}
  1. 定義 mybatis 對映器。對映器是一個 java 介面,它將儲存 SQL 查詢並將方法呼叫轉換為 JDBC 查詢。如果正在使用預設的 Spring Boot HSQLDB 資料庫,則可以建立以下查詢。 (涉及表;它只返回使用使用者提供的引數構建的字串)。
public interface HelloWorldMapper {

    @Select("VALUES ('Hello ' || #{origin})")
    String getString(@Param("origin") String origin);

} 
  1. 註冊現有的對映器,以便 Mybatis 和 Spring 可以瞭解它們。將 @MapperScan 新增到 spring java 配置中,其名稱為包含 mapper 介面的 root 包。此註釋將自動將介面註冊為 spring bean,可以輕鬆地將其注入應用程式的任何位置。
    @Autowired
    private HelloWorldMapper helloWorldMapper;

    // invoking the mapper method
    helloWorldMapper.getString("World");

這是完整的 Spring 配置類,帶有查詢的測試呼叫:

package com.example;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.lang.annotation.*;

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
@MapperScan("com.example")
public class DemoApplication {

    @Autowired
    private HelloWorldMapper helloWorldMapper;

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

    @PostConstruct
    public void init() {
        System.out.println(helloWorldMapper.getString("World"));
    }

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

}