MyBatis-Spring-Boot 使用总结

 
mybatis开发团队为Spring Boot 提供了  MyBatis-Spring-Boot-Starter

首先,MyBatis-Spring-Boot-Starter will:html

  • Autodetect an existing DataSource.
  • Will create and register an instance of a SqlSessionFactoryBean passing that DataSource as an input.
  • Will create and register an instance of a SqlSessionTemplate got out of the SqlSessionFactoryBean.
  • Autoscan your mappers, link them to the SqlSessionTemplate and register them to Spring context so they can be injected into your beans.
 
就是说,使用了该Starter以后,只须要定义一个DataSource便可,它会自动建立使用该DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。会自动扫描你的Mappers,链接到SqlSessionTemplate,并注册到Spring上下文中。
 
MyBatis-Spring-Boot-Application的配置参数也是保存在application.properties文件中,使用前缀 mybatis 。
Property Description
config-location MyBatis xml config file (optional)
mapper-locations Mapper xml config files (optional)
type-aliases-package Package to search for type aliases (optional)
type-handlers-package Package to search for type aliases (optional)
executor-type Executor type: SIMPLE, REUSE, BATCH (optional)
configuration A MyBatis Configuration bean. About available properties see the MyBatis reference page. NOTE This property cannot use at the same time with the config-location.       
(Starter)设置mapper有两种方法:
①使用config-location指定一个config xml,在里面设置 mapper 和 alias 。见例子1。
②使用type-aliases-package,须要配合自动扫描Mappers使用。
 
针对第二种,须要注意的是,若是想要自动扫描Mappers,须要在Mapper接口上标注@Mapper,不然失败。另外,还须要在application.properties文件中声明:mybatis.type-aliases-package 。
 
mapper-locations这个配置参数仅当mapper xml与mapper class不在同一个目录下时有效。因此通常能够忽略。
 
 
例子1(经过 mybatis.config-location 指定config xml,而后在里面设置别名和mapper包):
#application.properties
mybatis.config-location=mybatis-config.xml
<?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>
    <typeAliases>
        <package name="sample.mybatis.domain"/>
    </typeAliases>
    <mappers>
        <mapper resource="sample/mybatis/mapper/CityMapper.xml"/>
        <mapper resource="sample/mybatis/mapper/HotelMapper.xml"/>
    </mappers>
</configuration>
 
例子2(经过 mybatis.type-aliases-package 和 @Mapper 来配置mybatis):
#application.properties
mybatis.type-aliases-package=com.expert.pojo
package com.expert.dao;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import com.expert.pojo.User;
@Mapper
public interface UserMapper   {
//    @Select("SELECT * FROM user WHERE id = #{ id }")
    User getById(String id);
    
    @Select("SELECT * FROM user WHERE id = #{ id }")
    User getById2(String id);
}

 

注意:@Alias("xxx") 是用来设置别名,而非用于扫描。
相关文章
相关标签/搜索