Mybatis
支持的映射方式有基于xml的mapper.xml
文件、基于java的使用Mapper
接口类。接口方法注解主要是四个:@Insert、@Delete、@Update、@Select
从mybatis3.4.0开始加入了@Mapper
注解,目的就是为了不再写mapper映射文件。
在接口类上添加了@Mapper
,在编译之后会生成相应的接口实现类。
@Mapper
public interface UserMapper {
@Insert("insert into user(name) values(#{name})")
@Options(keyProperty="id",keyColumn="id",useGeneratedKeys=true)
public void save(User user);
}
使用@Mapper
可以不在包扫描而创建dao接口实现类对象。如果再搭配上注解式sql可以实现无mapper.xml。
spring.xml
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定扫描的包 -->
<property name="basePackage" value="com.hd.**.dao" />
<!-- 如果你的项目中只有一个SqlSessionFactory(或SqlSessionTemplate),就可以不用指定,因为MapperScannerConfigurer会自动装配SqlSessionFactory(或 SqlSessionTemplate);否则就必须指定 -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<!-- 注意:若同时配置了SqlSessionFactory和SqlSessionTemplate,则系统会选择SqlSessionTemplate,作废SqlSessionFactory -->
<property name="sqlSessionTemplateBeanName" value="sqlSessionTemplate"></property>
<!-- 含有特定注解的接口,一般设置为Spring提供的@Repository或Mybatis提供的@Mapper,当然也可以自定义注解 -->
<property name="annotationClass" value="org.springframework.stereotype.Repository"></property>
</bean>
MapperScannerConfigurer
postProcessBeanDefinitionRegistry()
方法(继承自BeanDefinitionRegistryPostProcessor
),根据自己的各属性值创建一个ClassPathMapperScanner
对象,并执行其scan()
方法。注:接口不用标注 @Mapper/@Component注解(除非指定了annotationClass属性)ClassPathMapperScanner
doScan()
方法,对指定的mapper
包进行扫描,解析每个Mapper
接口,然后封装成BeanDefinition
,但是这里BeanDefinition
对应的class类型并不是Mapper接口对应的类型,而是MapperFactoryBean
类型,即Mapper接口注册到IOC容器的都是MapperFactoryBean
类型。MapperFactoryBean
getObject()
方法。这种方式与老的xml方式的原理是完全一样的。
/**
* 使用JavaConfig时,使用此注释注册MyBatis mapper接口
*/
@Import(MapperScannerRegistrar.class)
public @interface MapperScan {
}
@MapperScan("com.xx.yy.mapper")
@Import(MapperScannerRegistrar.class)
MapperScannerRegistrar
ImportBeanDefinitionRegistrar
接口,重写registerBeanDefinitions()
,方法内获取注解元数据的@MapperScan
注解的属性值,根据这些属性值注入一个MapperScannerConfigurer-Bean
,beanDefinition
:根据@MapperScan
注解的属性值MapperScannerConfigurer
ClassPathMapperScanner
MapperFactoryBean
总结:需要在启动类上使用
@MapperScan
,并指定扫描Mapper的base package
,还可以指定标有某个注解的接口(若不指定,则接口上不需要任何注解)。
META-INF/spring.factories
文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration
MybatisAutoConfiguration
MybatisAutoConfiguration
才会起作用SqlSessionFactory-Bean·、SqlSessionTemplate-Bean
,会分别创建一个MapperFactoryBean-Bean
, MapperScannerConfigurer-Bean
,则会导入AutoConfiguredMapperScannerRegistrar
AutoConfiguredMapperScannerRegistrar
registerBeanDefinitions()
方法,将注入一个MapperScannerConfigurer-Bean
到了IOC容器中,注入的这个bean的beanDefinition
:扫描Spring Boot
的base package
下(所以不需要再指定扫描Mapper的base package)的带有@Mapper
注解(所以接口需要标注 @Mapper注解)的classMapperScannerConfigurer
@MapperScan
@Mapper
MyBatis mapper
总结:不需要在启动类上使用
@MapperScan
,只需要确保Mapper接口在Spring Boot的base package
下(一般情况下都在),且接口上标有@Mapper
注解即可!