基于IOC容器實(shí)現(xiàn)管理mybatis過程解析
SqlSessionFactory是mybatis的基礎(chǔ)中的基礎(chǔ),必須實(shí)例!
邏輯思路:
減少代碼冗余,需要封裝mybatisAPI。 可以注冊(cè)SqlSessionFactoryBean,來完成SqlSessionFactory的實(shí)例化。它的實(shí)例化需要(依賴)'mybatis-config.xml'文件,
其中有三大抽象:1、數(shù)據(jù)源;2、別名;3、注冊(cè)mapper
可以把依賴(作為屬性)注入(DI)到SqlSessionFactoryBean中,來完成SqlSessionFactory的實(shí)例化。
pom:junit、webmvc、mysql-connector、spring-jdbc、mybatis、mybatis-spring、lombok
1、spring-dao.xml:bean約束
<beans xmlns='http://www.springframework.org/schema/beans' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:context='http://www.springframework.org/schema/context' xsi:schemaLocation='http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd'></beans>
2、db.properties
jdbc.driver=com.mysql.cj.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/數(shù)據(jù)庫?serverTimezone=GMT%2B8jdbc.username=rootjdbc.password=123
3、引入數(shù)據(jù)庫配置文件
<context:property-placeholder location='classpath:db.properties'/>
4、從spring自帶jdbc配置數(shù)據(jù)源
<bean class='org.springframework.jdbc.datasource.DriverManagerDataSource'> <property name='driverClassName' value='${jdbc.driver}'/> <property name='url' value='${jdbc.url}'/> <property name='username' value='${jdbc.username}'/> <property name='password' value='${jdbc.password}'/></bean>
5、利用SqlSessionFactoryBean獲取配置SqlSessionFactory實(shí)例
<bean class='org.mybatis.spring.SqlSessionFactoryBean'> <property name='dataSource' ref='dataSource'/> <property name='mapperLocations' value='classpath*:mapper/*.xml'/> <property name='typeAliasesPackage' value='pojo'/> </bean>
6、掃描dao包,同時(shí)生成sqlsessionTemplate和注入mapper接口的實(shí)現(xiàn)類
<bean class='org.mybatis.spring.mapper.MapperScannerConfigurer'> <property name='basePackage' value='dao' /> <property name='sqlSessionFactoryBeanName' value='sqlSessionFactory'/></bean>
7、加載spring-dao.xml獲取上下文,從而為dao接口自動(dòng)裝配
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext('spring/spring-dao.xml');StudentDao studentDao = (StudentDao) context.getBean('studentDao');List<Student> students = studentDao.selectAll();
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Oracle數(shù)據(jù)庫中臨時(shí)表的進(jìn)一步深入研究2. 詳解sql server中數(shù)據(jù)庫快照工作原理3. Mysql優(yōu)化方法詳細(xì)介紹4. 詳解mysql 中的鎖結(jié)構(gòu)5. 盤點(diǎn)SqlServer 分頁方式和拉姆達(dá)表達(dá)式分頁6. 為SQLite3提供一個(gè)ANSI到UTF8的互轉(zhuǎn)函數(shù)7. 初識(shí)SQLITE3數(shù)據(jù)庫8. Docker 安裝 MySQL 并實(shí)現(xiàn)遠(yuǎn)程連接教程9. mysql的MVCC多版本并發(fā)控制的實(shí)現(xiàn)10. MyBatis 實(shí)現(xiàn)批量插入和刪除中雙層循環(huán)的寫法案例
