Question

we are running a JavaEE 6 Environment with EclipseLink and JBoss Weld. For the EntityManager, we currently are using the @ConversationScoped scope and it works very well for the JSF interactions.

We now want to include a @Schedule method for some automated checking of data (check for deadlines etc.). However, i don't know whether this is even possible, as the automated call doesn't seem to create a conversation. This is currently our approach:

@Stateless
public class Scheduler

  @Inject
  private CampaignService campaignService; 
    // CampaignService is @ApplicationScoped and uses an EntityManager

  @Schedule(second="*/3", ...)
  public void checkDeadlines(){
    campaignService.getAll() // fetches all campaigns from EntityManager
    ...
  }

}

However, the injection does not work as long as the EntityManager is @ConversationScoped. (ContextNotActiveException)

Is there a possibility to "create" a conversation other than by calling some JSF? Or is the only possibility creating a custom scope, as in How to use CDI-@SessionScoped without a http-session?

Was it helpful?

Solution

If you're going to be using schedulers your best solution is to use @PersistenceContext to get an EntityManager. The other option is to not use a conversation scoped entitymanager (which should be considered bad practice anyway), and use a default scoped or request scoped entitymanager.

I say a conversation scoped entitymanager is bad practice because it can easily lead to lazy initialization issues, detached entities and memory leaks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top