当我们使用MyBatis时,往往会有以下操作:
1,添加@MapperScan注解,或者在配置文件中使用<mybatis:scan>进行设置。这一步设置的是需要扫描的Mapper文件路径,比如这样:
@Configuration
@EnableTransactionManagement
@MapperScan({"com.macro.mall.mapper","com.macro.mall.dao"})
public class MyBatisConfig {
}
2,编写Mapper.java接口文件,比如:
public interface OmsOrderDao {
List<OmsOrder> getList(@Param("queryParam") OmsOrderQueryParam queryParam);
int delivery(@Param("list") List<OmsOrderDeliveryParam> deliveryParamList);
OmsOrderDetail getDetail(@Param("id") Long id);
}
Mapper接口类可以不用注解,也可以不用写实现类。
在ServiceImpl或者其他什么类中,添加Mapper接口作为属性,并且使用@Autowired注解,比如:
@Service
public class OmsOrderServiceImpl implements OmsOrderService {
@Autowired
private OmsOrderDao orderDao;
...
}
3,在配置文件中指定Mapper.xml文件的路径,比如在SpringBoot的yml格式配置文件中可以这么写:
mybatis:
mapper-locations:
- classpath:dao/*.xml
- classpath*:com/**/mapper/*.xml
4,编写Mapper.xml文件,与Mapper.java文件对应,比如在xml文件中使用以下写法:
<mapper namespace="com.macro.mall.dao.OmsOrderDao">
就可以关联到具体的Mapper接口。
另外,我们可以在Mapper.java中的方法上使用注解并编写动态sql,实现和Mapper.xml文件一样的效果。
5,调用Mapper接口。
使用起来并不难,下面一系列文章主要关注的就是,我们做的这些诸多配置和操作,从Spring和MyBatis源码的角度,是如何生效的。
因此,接下来的源码分析将按照SpringIOC的加载顺序,分析以下几个关键点的部分源码:
1,@MapperScan注解生效,根据配置路径扫描Mapper接口文件,创建BeanDefinition。
2,@Autowired注解生效,创建Mapper接口代理,注入sqlSessionFactory和sqlSessionTemplate。
3,注入sqlSessionFactory时,根据配置路径扫描xml文件,和Mapper接口代理绑定。
4,mybatis配置项的加载过程
5,调用Mapper接口时,使用接口代理完成数据库查询等操作。