ericj
ericj

Reputation: 2301

Executes the @PostConstruct method of a stateful session bean not in a transaction (in a Arquillian test)?

I have a stateless session bean,

@Stateless
public class MyService {

    @PersistenceContext
    private EntityManager entityManager;

    @PostConstruct
    public void init() {
        Language  language=new Language();
        language.setName("Foo");
        entityManager.persist(language);
    }
    ...

In a Arquillian test I have a CDI bean (@RequestScoped bean), which @Injects this service. This test runs OK.

But when I change this bean to a @Stateful bean, I get error messages:

Caused by: javax.persistence.TransactionRequiredException: WFLYJPA0060: Transaction is required to perform this operation (either use a transaction or extended persistence context)
    at service.MyServiceTest.testStateful(MyServiceTest.java:71)

When I put a @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) annotation on the @PostConstruct method, the test runs OK. But this is not what I want to do.

Also, I can remove the @Postconstruct from the init method, and call the init method explicitly in the Arquillian test. Then the init method is in a transaction.

So runs the @PostConstruct method of a stateful session beans not in a transaction, and of a stateless bean it does?

Upvotes: 1

Views: 624

Answers (1)

Steve C
Steve C

Reputation: 19445

The EJB 3.2 Core Contracts and Requirements Specification states the following in §8.3.7:

For a stateful session bean’s PostConstruct, PreDestroy, PrePassivate or PostActivate lifecycle callback interceptor methods, only the REQUIRES_NEW and NOT_SUPPORTED transaction attributes may be used.

So you can only have either a brand new transaction, or none at all.

If you're trying to get around this then you're not emulating your runtime environment.

Upvotes: 1

Related Questions