【Spring 框架(自學)】Day07(事務管理)已完結--2022/4/8
阿新 • • 發佈:2022-04-08
Spring的事務註解管理(事務管理)
Spring開啟事務,只適合中小型專案的開發,有兩大步驟:
- 宣告事務管理器:DataSourceTransactionManager
- 連線資料庫,指定資料來源(事務的提交回滾)
- 開啟事務註解驅動:annotation-driven(匯入字尾為tx的)
- 傳入事務管理器的id
//定義實體類對映資料庫
//定義持久層Dao介面,書寫方法
<!--用Mybatis對映持久層實現方法-->
//定義業務層Service介面,定義介面實現類
<!--配置Spring容器--> <!-- 1 .宣告database配置檔案:property-placeholder--> <!-- 2 .宣告資料來源,連線資料庫 :DruidDataSource <!--宣告資料庫連線的資訊:property <!--資料庫最大連線數:property --> <!-- 3 .宣告SqlSessionFactory:SqlSessionFactoryBean 3.1 傳入資料來源:dataSource 3.2 mybatis配置檔案交給spring容器管理:configLocation --> <!-- 4 .將持久層(Dao)交給Spring容器管理,建立Mapper物件:MapperScannerConfigurer 4.1 傳入SqlSession,得到getMapper()方法:sqlSessionFactoryBeanName 4.2 指定持久層(Dao)所在的包名,併為每個Mapper建立物件:basePackage MapperScannerConfigurer屬性:會為所有Dao層介面執行getMapper()方法 --> <!-- 5 .建立Service物件,將Dao層物件賦予給Service層:property 實現功能、層級的分離 --> <!--宣告事務管理器物件:DataSourceTransactionManager--> <bean id = "tranSactionManager" class = "...DataSourceTransactionManager"> <!--傳入資料來源:dataSource--> </bean> <!--開啟事務註解驅動--> <tx:annotation-driven transaction-manager="傳入宣告事務管理器物件"></tx:annotation-driven>
//Service介面實現類在public上加入註解 /* @Transactional( propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false, rollbackFor = { NullPointerException.class,Exception.class } ) */ //@Transactional @Override public void buyGoods(Integer id, Integer nums) { //購買商品 Sale sale = new Sale(); sale.setGid(id); sale.setNums(nums); saleMapper.insertSale(sale); //對商品進行查詢 讓後進行更新 Goods goods = goodsMapper.selectGoods(id); if (goods == null){ throw new NullPointerException(id+"商品不存在"); }else if (goods.getAmount() < nums){ throw new Exception(id+"商品數量不足"); } Goods buyGoods = new Goods(); buyGoods.setId(id); buyGoods.setAmount(nums); goodsMapper.updateGoods(buyGoods); }
AspectJ的事務註解管理(事務管理)
/*
省略Spring容器配置之前的所有配置,同上,無任何改變
*/
<!--配置Spring容器--> <!--宣告事務管理器物件:DataSourceTransactionManager--> <bean id = "transactionmanager" class = "...DataSourceTransactionManager"></bean> <!--開啟事務註解驅動--> <tx:advice id = "myAdvice" transaction-manager="傳入宣告事務管理器物件"> <!--配置事務的屬性--> <tx:attributes> <!--給具體方法配置事務,且method可以擁有多個 name:完整的方法名稱,也可以用萬用字元*代替 propagation:傳播行為 isolation:隔離級別 rollback-for:你指定的異常類名(全限定類名),遇到異常時回滾 --> <tx:method name = "方法名" propagation="REQUIRED" isolation="DEFAULT" rollback-for="java.lang.NullPointerException,com.springexer.Except.Exception"> </tx:method> </tx:attributes> </tx:advice> <!--配置aop((Aspect註解方法)--> <aop:config> <!--找到檔案所在地 com.xx.service com.xxx.service com.service --> <aop:pointcut id="myPt" expression="execution(* *..Service.*.*(..))"/> <!--配置增強器:關聯advice和pointcut advice-ref:繫結事務註解驅動 pointcut-ref:切入點表示式的id --> <aop:advisor advice-ref="myAdvice" pointcut-ref="myPt"></aop:advisor> </aop:config>
Spring整合Mybatis與Web
回頭再看