mybatis開發團隊為Spring Boot 提供了
MyBatis-Spring-Boot-Starter 。
首先,MyBatis-Spring-Boot-Starter will:
- 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") 是用來設置別名,而非用於掃描。
