依赖安装
2.1、Maven 安装如下:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
2.2、Gradle 安装如下:
dependencies {
compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.1")
}
大致功能
众所周知,MyBatis的核心有两大组件:SqlSessionFactory 和 Mapper 接口。前者表示数据库链接,后者表示SQL映射。当我们基于Spring使用MyBatis的时候,也要保证在Spring环境中能存在着两大组件。
MyBatis-Spring-Boot-Starter 将会完成以下功能:
1、Autodetect an existing DataSource
自动发现存在的DataSource
2、Will create and register an instance of a SqlSessionFactory passing that DataSource as an input using the SqlSessionFactoryBean
利用SqlSessionFactoryBean创建并注册SqlSessionFactory
3、Will create and register an instance of a SqlSessionTemplate got out of the SqlSessionFactory
创建并注册SqlSessionTemplate
4、Auto-scan your mappers, link them to the SqlSessionTemplate and register them to Spring context so they can be injected into your beans
自动扫描Mappers,并注册到Spring上下文环境方便程序的注入使用
1
MyBatis-Spring-Boot-Starter会自动找到被@Mapper注解的接口。使用@MapperScan可以指定Mapper接口的位置,免去每个接口都要@Mapper
可以获取sqlSession,具体为SqlSessionTemplate的一个实例。
@Component
public class CityDao {
private final SqlSession sqlSession;
public CityDao(SqlSession sqlSession) {
this.sqlSession = sqlSession;
}
public City selectCityById(long id