0

I have an EAR application with an EJB module, that contains one persistence unit and many EJBs (as service and DAO layer).

@Stateless
public class BranchDAO {
    @PersistenceContext
    private EntityManager entityManager;
}

But DAOs as Stateless beans are not recommended. So I create this annotation using CDI:

@Dependent
@Stereotype
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DAO {
}

After my DAO is changed to not use @Stateless:

@DAO
public class BranchDAO {
    @PersistenceContext
    private EntityManager entityManager;
}

But the Glassfish doesn't bring up the entity manager when the application starts. And when I call the DAO, the entity manager is in an illegal state.

java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName null

This error only occurs in Glassfish 3, but not in JBoss AS 6. Using JBoss AS 6 I can see the Hibernate logs in startup (but I don't see them with Glassfish).

As a temporary solution I created an Stateless bean with the content below. It's not beautiful solution, but works fine in Glassfish.

@Stateless
@Startup
public class AutoStartEntityManager {

    @PersistenceContext
    private EntityManager entityManager;

}

So, how I can force Glassfish to bring up EntityManager when I'm not using @Stateless in my DAO?

Dennis Meng
  • 5,109
  • 14
  • 33
  • 36
Otávio Garcia
  • 1,372
  • 1
  • 15
  • 27

1 Answers1

1

Try specifying explicitly the unitName:

@PersistenceContext(unitName="yourJPAUnitName")
private EntityManager manager;

(A sidenote - are you sure you need the DAO in dependent scope? Shouldn't it be singleton?)

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • I've tried this way (with unitName), but without success (same problem occurs). I'm using DAO as dependent to inherit scope from caller. I'm right? Regards. – Otávio Garcia Feb 02 '11 at 17:18
  • yes, but that will mean you will have as many DAO instances as callers. And this is not needed. – Bozho Feb 02 '11 at 17:19