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") 是用來設置別名,而非用於掃描。
相關文章
相關標籤/搜索