Spring整合Mybatis思路的示例分析
这篇文章主要介绍Spring整合Mybatis思路的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
引入相关依赖Spring
Myabtis
mysql
Mybatsi-spring
如何整合?Spring:
项目管理框架,主要是用来负责项目中组件对象的创建,使用,销毁。
Mybatis:
持久层框架,主要是用来简化原始jdbc技术对数据库访问操作。
== >整合思路:通过Spring框架接管Mybatis框架中核心对象的创建。
Mybatis框架中核心对象是谁?sqlSession?
SqlSessionFactory?
SqlSessionFactoryBuilder?
dao?
最核心的对象必然是:SqlSessionFactory。
SqlSessionFactoryBuilder的作用就是读取解析配置文件==【数据源配置,mapper文件配置】==,来创建SqlSessionFactory。
SqlSession的创建又依靠于SqlSessionFactory。
== > SqlSessionFactory是最核心的对象。
SM整合整合思路:通过Spring框架接管Mybatis中核心的SqlSessionFactory对象的创建。
SqlSessionFactory是简单对象还是复杂对象呢?
如果是简单对象
<beanid=""class=""/>
如果是复杂对象
通过查看源码得知,SqlSessionFactory是一个接口类型的复杂对象。
如何创建?
is=Resources.getResourceAsStream("mybatis-config.xml");sqlSessionFactory=newSqlSessionFactoryBuilder(),build(is);
1).SqlSessionFactory(Factory)BeanimplementsFactoryBean<SqlSessionFactory>{SqlSessionFactorygetObject(){is=Resources.getResourceAsStream("mybatis-config.xml");sqlSessionFactory=newSqlSessionFactoryBuilder(),build(is);}ClassgetClass(){returnSqlSessionFactory.class;}booleanisSingleton(){returntrue;}}2).工厂管理SqlSessionFactory<beanid="sqlSessionFactory"class="xxx.SqlSessionFactoryBean">3).工厂获取SqlSessionFactorysf=context.getBean("sqlSessionFactory");
写完之后,我们可以发现,这段代码是固定不变的,这个项目要写,别的项目也要写。
于是Mybatis官方替我们写好了,对这段代码进行了封装:Mybatis-spring.jar。
jar包里提供了一个类:SqlSessionFactoryBean。
我们以后只要引Mybatsi-spring依赖就可以了,不用在自己去写了。
值得注意的是:mybatis官方提供SqlSessionFactoryBean,不在使用mybaits主配置文件。
主配置文件的核心就是【数据源】【mapper文件的注册】
所以我们要注入数据源对象,引入druid依赖,注入mapper文件的位置。【DI思想,依赖注入】
<!--配置Spring.xml文件--><!--创建数据源对象--><beanid="dataSource"class="com.alibaba.druid.pool.DruidDataSource"><propertyname="driverName"value="com.mysql.cj.jdbc.Driver"/><propertyname="url"value="jdbc:mysql://localhost:3306/xxx"/><propertyname="username"value="root"/><propertyname="password"value="root"/><bean/><!--创建SqlSessionFactory对象--><beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><!--注入数据源对象--><propertyname="dataSource"ref="dataSource"/><!--注入mapper文件的位置--><propertyname="mapperLocations"><array><value>.....</value></array></property><bean/>
以上是“Spring整合Mybatis思路的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。