3

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?

Community
  • 1
  • 1
bmurauer
  • 989
  • 8
  • 24
  • How about firing some CDI events from your `Scheduler` combined with an `@Observes` method in your conversation scoped beans? – rdcrng Jul 02 '13 at 13:16
  • With the ConversationScoped EntityManager, this still didn't work for us. However, we switched to a Default Scoped one (as LightGuard suggested) and now the Events are a clean solution. – bmurauer Jul 04 '13 at 12:32

1 Answers1

2

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.

LightGuard
  • 5,298
  • 19
  • 19
  • We indeed ended up with a default scoped EntityManager. Had some bad thinking when designing our architecture. Thanks! – bmurauer Jul 04 '13 at 12:31