Aspectj如何驱动Hibernate Transaction

时间:2014-07-26 16:03:18

标签: hibernate transactions aspectj

我将AspectJ写入自动驱动程序hibernate Transaction:

public aspect HiberAspectj {

    before() :  execution(@AnnHibernateSession * *.*()) 
             && !cflowbelow( execution(@AnnHibernateSession * *.*())   )   
             && !within(HiberAspectj) {
        System.out.println("Start hibernate transaction");
    }

    after( ) returning() : execution(@AnnHibernateSession * *.*()) 
     && !cflowbelow( execution(@AnnHibernateSession * *.*())   )   
     && !within(HiberAspectj) {
        System.out.println("Commit");
    }

    after() throwing() : execution(@AnnHibernateSession * *.*()) 
     && !cflowbelow( execution(@AnnHibernateSession * *.*())   )   
     && !within(HiberAspectj) {
        System.out.println("Rollback");
    }
}

注释:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AnnHibernateSession {

}

DAO班级:

public class DAO {

    public static void other() {
        System.out.println(" - other");
    }

    @AnnHibernateSession
    public static void updateEmp() {
        System.out.println(" - Update Emp");
    }

    @AnnHibernateSession
    public static void updateDept() {
        System.out.println(" - Update Dept");
    }
}

上课测试:

public class Test {

    // Call method OK (One Transaction create!!)
    @AnnHibernateSession
    public static void callAction1()  {
        DAO.updateDept();
        DAO.other();
        DAO.updateEmp();
    }

    // No @AnnHibernateSession
    // Call method not OK (2 Transaction Create!!)
    public static void callAction2()  {
        DAO.updateDept();
        DAO.other();
        DAO.updateEmp();
    }

    public static void main(String[] args) {
        callAction1();
        System.out.println(" ------------------ ");
        callAction2();

    }

}

我运行类Test并得到Result:

Start hibernate transaction
 - Update Dept
 - other
 - Update Emp
Commit
 ------------------ 
Start hibernate transaction
 - Update Dept
Commit
 - other
Start hibernate transaction
 - Update Emp
Commit

调用方法callAction1:一个事务创建。

方法callAction2调用:两个事务创建(我不喜欢)。

帮帮我。 我如何编辑方面callAction2的方面HiberAspectj像callAction1 ??

一样工作

0 个答案:

没有答案