@ManagedBean and @Transactional - bug in Spring? W

2019-08-27 21:29发布

问题:

I had the following JSF backing bean in my Webapp

@ManagedBean
class MyBackingBean implements Serializable {

    private MyHibernateRepository repository;
    ...

    @Transactional 
    public void save() {
        ....
        repository.save(myObject);
    }

}

When it gets to the repository.save method call - I get the following error

no transaction is in progress

I've got two questions

  1. Is this because of a bug like this?
  2. I believe there are two workarounds - are there any others?

2.1 First workaround - using

transactionTemplate.execute(new TransactionCallbackWithoutResult() {
  protected void doInTransactionWithoutResult(TransactionStatus status) {
    repository.save(myObject);
  }
});

2.2 Second workaround

Create a helper class and annotate that instead.

2.3 (A possible third workaround would be to annotate @Transactional on a method of an inner class This is quite similar to 2.2).

回答1:

When using Spring annotations (I know that @Transactional is a Sun standard - but you need an implementation) - Spring uses AOP to annotate to the class to add the transaction handling code. This only works for Spring beans. If your class is a backing bean for JSF - the Mojarra framework won't insert its own transaction handling code to this annotation.

Short answer - @Transactional works for beans loaded by Spring. Otherwise you need to find a framework that supports it or assume it won't work.