MFC编程实例:从零实现MVC框架之AOP事务(5)
小职 2018-07-05 来源 : 阅读 1066 评论 0

摘要:本文主要向大家介绍了MFC编程实例:从零实现MVC框架之AOP事务(5),通过具体的内容向大家展示,希望对大家学习MFC编程实例有所帮助。

本文主要向大家介绍了MFC编程实例:从零实现MVC框架之AOP事务(5),通过具体的内容向大家展示,希望对大家学习MFC编程实例有所帮助。

利用动态代理实现AOP。另外我么写一个注解,表明哪个类下的方法需要加事务(为了简单偷懒了,哈...)。加上注解后

此类的每个方法都会加事务。

这其中还多了一个事务执行器的概念,事务执行器和一般执行器的区别就是 事务执行器中数据库连接是不自动提交的。

而一般执行器中的连接是自动提交的。 我们使用ThreadLocal来保存事务执行器,来保证每个线程都有自己的事务执行器。

下面看具体实现。

注解

[java] view plain copy

1. package com.hc.annotation;  

2.   

3. import java.lang.annotation.ElementType;  

4. import java.lang.annotation.Retention;  

5. import java.lang.annotation.RetentionPolicy;  

6. import java.lang.annotation.Target;  

7. /** 

8.  * 事务类注解 

9.  * @author chuer 

10.  * @date 2014-7-16 下午2:28:12 

11.  * @version V1.0 

12.  */  

13. @Retention(RetentionPolicy.RUNTIME)  

14. @Target({ElementType.TYPE})  

15. public @interface Transaction {  

16.   

17. }  


抽象实体类修改setExecute和rollBack方法(AbstractEntity)

[java] view plain copy

1. @Override  

2.     public void setExecute() {  

3.         AbstractExecute<AbstractEntity> execute2 = TransactionManager.getInstance().getExecute();  

4.         if(execute2 != null){  

5.             execute = execute2;  

6.         }else{  

7.             execute = ExecuteFactory.getExecute();  

8.         }  

9.     }  

10.   

11.     @Override  

12.     public void rollBack() {  

13.         AbstractExecute<AbstractEntity> execute2 = TransactionManager.getInstance().getExecute();  

14.         if(execute2 != null){  

15.             execute2.rollback();  

16.         }  

17.     }  

18.       

事务类缓存

[java] view plain copy

1. package com.hc.transaction;  

2.   

3. import java.io.File;  

4. import java.lang.reflect.Proxy;  

5. import java.util.ArrayList;  

6. import java.util.List;  

7. import java.util.concurrent.ConcurrentHashMap;  

8.   

9. import com.hc.annotation.Transaction;  

10. /** 

11.  *  

12.  * @author chuer 

13.  * @date 2014-7-16 下午3:32:49 

14.  * @version V1.0 

15.  */  

16. public class TransactionProxyCache {  

17.   

18.     public static ConcurrentHashMap<Class<?>,Object> cache = new ConcurrentHashMap<>();  

19.     public static final String PAKAGE = "com";//扫描的包名 根据自己的包名进行修改  

20.     public static final String PAKAGE_SOURCE = "/com/hc";//扫描的包名 根据自己的包名进行修改  

21.     public static final String SECOND_PAKAGE = "com.hc";//扫描的包名 根据自己的包名进行修改  

22.     static{  

23.         //扫描项目下所有的类  

24.         try {  

25.             init();  

26.         } catch (Exception e) {  

27.             e.printStackTrace();  

28.         }  

29.     }  

30.       

31.     private static void init(){  

32.         String path = TransactionProxyCache.class.getResource(PAKAGE_SOURCE).getPath();  

33.         List<String> classes = new ArrayList<String>();  

34.         getAllClasses(new File(path),classes);  

35.           

36.         //实例化  

37.         for(String p : classes){  

38.             try{  

39.                 Class<?> cls = Class.forName(p);  

40.                 if(cls.isAnnotationPresent(Transaction.class)){  

41.                     Object newInstance = cls.getConstructor(new Class[]{}).newInstance(new Object[]{});  

42.                     Object newProxyInstance = Proxy.newProxyInstance(newInstance  

43.                             .getClass().getClassLoader(), newInstance.getClass()  

44.                             .getInterfaces(), new AOPHandler(newInstance));  

45.                     cache.put(cls, newProxyInstance);  

46.                 }  

47.             }catch(Exception e){  

48.                 e.printStackTrace();  

49.             }  

50.         }  

51.     }  

52.       

53.     private static void getAllClasses(File file,List<String> files){  

54.         if(file.isDirectory()){  

55.             File[] listFiles = file.listFiles();  

56.             for(File f : listFiles){  

57.                 getAllClasses(f,files);  

58.             }  

59.         }else{  

60.             if(file.getAbsolutePath().endsWith(".class")){  

61.                 String substring = file.getAbsolutePath().substring(file.getAbsolutePath().indexOf(PAKAGE));  

62.                 substring = substring.substring(0, substring.lastIndexOf('.'));  

63.                 if(substring.contains("/")){  

64.                     substring = substring.replaceAll("/", ".");  

65.                 }else{  

66.                     substring = substring.replaceAll("\\\\", ".");  

67.                 }  

68.                 if(substring.contains(SECOND_PAKAGE)){  

69.                     files.add(substring);  

70.                 }  

71.             }  

72.         }  

73.     }  

74.       

75.     public static void main(String[] args) {  

76.           

77.     }  

78.       

79. }  


动态代理AOP

[java] view plain copy

1. package com.hc.transaction;  

2.   

3. import java.lang.reflect.InvocationHandler;  

4. import java.lang.reflect.Method;  

5.   

6.   

7. public class AOPHandler implements InvocationHandler{  

8.   

9.     private Object obj;  

10.     public AOPHandler(Object obj){  

11.         this.obj = obj;  

12.     }  

13.       

14.     @Override  

15.     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {  

16.           

17.         //开启事务  

18.         System.out.println("begin transaction---");  

19.         TransactionManager.getInstance().beginTransaction();  

20.         //执行方法  

21.         method.invoke(obj, args);  

22.           

23.         //提交事务  

24.         TransactionManager.getInstance().commitTransaction();  

25.         System.out.println("end transaction---");  

26.           

27.         return null;  

28.     }  

29.   

30.       

31. }  

 

事务管理类

[java] view plain copy

1. package com.hc.core;  

2.   

3.   

4. public interface ITransaction {  

5.   

6.     public void beginTransaction();  

7.     public void commitTransaction();  

8.     public AbstractExecute<AbstractEntity> getExecute();  

9. }  


 

[java] view plain copy

1. package com.hc.transaction;  

2.   

3. import com.hc.core.AbstractEntity;  

4. import com.hc.core.AbstractExecute;  

5. import com.hc.core.ExecuteFactory;  

6. import com.hc.core.ITransaction;  

7. /** 

8.  * 事务管理 

9.  * @author chuer 

10.  * @version 2014-6-16  下午1:55:06 

11.  */  

12. public class TransactionManager implements ITransaction{  

13.   

14.       

15.     private static ThreadLocal<AbstractExecute<AbstractEntity>> local = new ThreadLocal<>();  

16.     private static TransactionManager manager = new TransactionManager();  

17.     private TransactionManager(){}  

18.       

19.     public static TransactionManager getInstance(){  

20.         return manager;  

21.     }  

22.       

23.     @Override  

24.     public void beginTransaction() {  

25.         AbstractExecute<AbstractEntity> execute = ExecuteFactory.getTransactionExecute();  

26.         execute.setAutoCommit(false);  

27.         local.set(execute);  

28.     }  

29.   

30.     @Override  

31.     public void commitTransaction() {  

32.         AbstractExecute<AbstractEntity> execute = getExecute();  

33.         execute.commit();  

34.         local.remove();  

35.     }  

36.   

37.     @Override  

38.     public AbstractExecute<AbstractEntity> getExecute() {  

39.         return  local.get();  

40.     }  

41.   

42.       

43.       

44. }  



事务类

[java] view plain copy

1. package com.hc.sample.service;  

2.   

3. import java.sql.SQLException;  

4.   

5. public interface UserService {  

6.   

7.     public void add()throws SQLException;  

8.       

9. }  


 

[java] view plain copy

1. package com.hc.sample.service;  

2.   

3. import java.sql.SQLException;  

4.   

5. import com.hc.annotation.Transaction;  

6. import com.hc.pool.IDPool;  

7. import com.hc.sample.entity.UserEntity;  

8.   

9. @Transaction  

10. public class UserServiceImpl implements UserService{  

11.   

12.     @Override  

13.     public void add() throws SQLException {  

14.         UserEntity user = new UserEntity();  

15.         user.setId(IDPool.getInstance().applyId());  

16.           

17.         user.setName("chujiinhui");  

18.           

19.         //持久化用户  

20.         user.persist();  

21.           

22.         //修改用户  

23.         user.setName("wangmanman");  

24.           

25.         //异常事务回滚  

26.     }  

27.   

28.       

29. }  


测试类

[java] view plain copy

1. package com.hc.sample.startup;  

2.   

3. import java.sql.SQLException;  

4.   

5. import com.hc.sample.service.UserService;  

6. import com.hc.sample.service.UserServiceImpl;  

7. import com.hc.transaction.TransactionProxyCache;  

8.   

9. public class TestTransaction {  

10.   

11.     /** 

12.      * @param args 

13.      * @throws SQLException  

14.      */  

15.     public static void main(String[] args) throws SQLException {  

16.           

17.         UserService userService = (UserService)TransactionProxyCache.cache.get(UserServiceImpl.class);  

18.           

19.         userService.add();  

20.     }  

21.   

22. }  


运行测试类,输出如下:

[plain] view plain copy

1. begin transaction---  

2. insert into user_m(id,name) values (?,?)  

3. update user_m set name=? where id=?  

4. end transaction---  

可以打断点,对比数据库查看事务的执行情况。

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言VC/MFC频道!

本文由 @小职 发布于职坐标。未经许可,禁止转载。
喜欢 | 1 不喜欢 | 0
看完这篇文章有何感觉?已经有1人表态,100%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程