使用 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);
    }

}