一、MyBatis与Spring整合
MyBatis与Spring框架通过MyBatis Spring模块进行整合。
整合原理:MyBatis的Mapper实例是通过动态代理创建的。与Spring框架整合后,MyBatis中的Mapper动态代理对象会作为Spring框架中的Bean注册到Spring容器中。
Bean的配置如下:
Spring配置Bean的方式有多种,例如XML文件、Java注解以及JavaConfig等方式。这里我们使用JavaConfig方式配置:
1.配置数据源对象
2.配置SqlSessionFactory对象
SqlSession是MyBatis提供的与数据库交互的接口,而SqlSession的创建依赖于SqlSessionFactory对象,因此我们需要创建SqlSessionFactory对象,
并通过Spring来管理SqlSessionFactory对象的生命周期。我们使用了MyBatis Spring模块中提供的SqlSessionFactoryBean来构建SqlSessionFactory对象。
3.配置SqlSessionTemplate对象
在使用MyBatis时,我们可以通过SqlSessionFactory对象的openSession()方法获取一个SqlSession对象,然后调用SqlSession对象提供的方法就可以与数据库进行交互了。
每次调用SqlSessionFactory对象的openSession()方法返回的是一个新的实例,MyBatis Spring模块提供了SqlSessionTemplate用于完成数据库交互,在整合Spring容器中只存在一个SqlSessionTemplate实例。
4.通过MapperScan注解扫描Mapper接口
在MyBatis中,Mapper对象是通过动态代理生成的,调用SqlSession对象的getMapper()方法每次返回的是一个新的代理对象。
MyBatis Spring模块提供了一个MapperScan注解,用于扫描特定包下的Ma