带有注释的多事务管理器弹簧配置

时间:2012-01-09 14:47:37

标签: spring jpa annotations spring-transactions

有两个bean JpaTransactionManager。

可以使用限定符表示法管理它们。

<bean id="transactionManagerConstant" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="constant"/>

    <qualifier value="first"/>
</bean>

<bean id="transactionManagerRelative" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="relative"/>
    <qualifier value="second"/>
</bean>

Java代码:

@Transactional("first")
public String saveWork(){

    em1.persist(work);
    work = (Work) ctx.getBean("work");
    return "/workLists.xhtml";
}

@Transactional("second")
public String saveEvent(){

    em2.persist(event);
    event = (Event) ctx.getBean("event");

    return "/eventLists.xhtml";
}

问题是:如何使用隔离级别或readOnly赋值? @Qualifier注释不起作用:

@Transactional(isolation = Isolation.SERIALIZABLE, propagation=Propagation.REQUIRED, readOnly = false)
@Qualifier("first")
public String saveWork(){

    em1.persist(work);
    work = (Work) ctx.getBean("work");
    return "/workLists.xhtml";
}

@Transactional(isolation = Isolation.SERIALIZABLE, propagation=Propagation.REQUIRED, readOnly = false)
@Qualifier("second")
public String saveEvent(){

    em2.persist(event);
    event = (Event) ctx.getBean("event");

    return "/eventLists.xhtml";
}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您应该将@Qualifier注释放在TransactionManager的成员上,而不是放在使用它的方法上。

以下假设em1em2是上面弹簧配置中定义的TransactionManager

@Autowired
@Qualifier("first")
private TransactionManager em1;

@Autowired
@Qualifier("second")
private TransactionManager em2;

@Transactional(isolation = Isolation.SERIALIZABLE, propagation=Propagation.REQUIRED, readOnly = false)
public String saveWork(){

    em1.persist(work);
    work = (Work) ctx.getBean("work");
    return "/workLists.xhtml";
}

@Transactional(isolation = Isolation.SERIALIZABLE, propagation=Propagation.REQUIRED, readOnly = false)
public String saveEvent(){

    em2.persist(event);
    event = (Event) ctx.getBean("event");

    return "/eventLists.xhtml";
}