1. 程式人生 > >【Spring與MyBatis整合】

【Spring與MyBatis整合】

準備工作(MyBatis基本):
1.匯入mybatis-spring、spring-jdbc、spring-tx三個jar包
2.編寫實體類、Mapper介面、Mapper.xml
3.編寫mybatis-config.xml核心配置檔案
整合步驟(基本):
1.匯入commons-dbcp、commons-pool
2.編寫applicationContext-mybatis.xml檔案,至少包含4個bean






classpath:xx/xxx/xxx/**/*.xml

3.Mapper進行查詢
	方式1:教材183(缺點:每個Mapper介面需要編寫實現類):
		<bean id="sqlSessionTemplate">
			<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
		<bean id="xxxMapper" class="xx.xxx.dao.xxxMapperImpl">
			<property name="sqlSession" ref="sqlSessionTemplate"/>
		sqlSession.selectList("xx.xxx.dao.user.XxxMapper.getList",xxx);

	改良1:教材185-186(缺點:每個Mapper介面需要編寫實現類):
		讓MapperImpl繼承自SqlSessionDaoSupport類
		<bean id="xxxMapper" class="xx.xxx.dao.xxxMapperImpl">
			<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
			
	改良2:教材187-188(優點:Mapper介面不用寫實現類;缺點:每個需要配置bean):
		Mapper.xml
		Mapper介面
		<bean id="xxxMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
			<property="mapperInterface" value="cn.smbms.dao.user.UserMapper"/>
			<property="sqlSessionFactory" ref="sqlSessionFactory"/>
	
	最終方案:教材188-189(Mapper不需要實現類,也不需要配置bean)
		<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
			<property name="basePackage" value="cn.smbms.dao,cn.smbms.dao2"/>
		Spring自動給Mapper介面的建立首字母小寫的bean,按該名稱注入即可

2.Spring和Mybatis整合的宣告式事務
2.1.一般情況下:增刪改的業務方法,傳播REQUIRED(預設值),查詢方法SUPPORTS
2.2.事務隔離級別:
未提交讀:
事務A修改的資料,未提交的情況下,事務B也能看見(最低隔離級別)
提交讀(又叫不可重複讀):
事務A修改的資料,未提交的情況下,事務B看不見

		併發量大的情況下,
		事務A查userName=wangchao的User資料,
		事務B把userName=wangchao修改為userName=hexingfeng
		事務A按userName=wangchao作為條件進行update,預期受影響的行數是1,實際0
		
		加行鎖for update(把符合查詢條件的行鎖住不讓其他事務修改)
	可重複讀(又叫幻影讀):insert、delete
		事務A查了性別=男的User資料,10條
		事務B插入了一條性別=男的User資料,9條
		事務A修改性別=男的資料,預期是受影響是10條,實際會得到9,就像產生幻影一樣
		
		加表鎖
	序列讀:
		資料最安全,併發效率最低,所有事務排隊
		
2.3.步驟:
	1.定義POJO、Mapper介面、Mapper.xml、Service介面和實現類
	2.編寫mybatis-config.xml 
	3.編寫applicationContext-mybatis.xml 
		<context:component-scan />
		<bean id="dataSource">
		<bean id="sqlSessionFactory">
		<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<bean id="txManager" class="">
		<tx:advice id="txAdvice" transactionManager="txManager">
			<tx:attributes>
				<tx:method name="add*">
		<aop:config>
			<aop:pointcut id="po" expression="">
			<aop:advisor advice-ref="txAdvice" pointcut-ref="po">