Search code examples
javadependency-injectionpersistenceguice

EntityManager don't being injected by Guice


I updated my createInjector call to include my JPAPersisteModule...

Guice.createInjector(new ApplicationModule(), new JpaPersistModule("simpleRestApplication"));

On my service, my DAO is injected without problem...

@Path("/users")
public class UserService {

    @Inject
    private UserDAO dao;

    public UserService() {
        Application.getInjector().injectMembers(this);
    }


}

On my UserDAOImpl, the Provider dont get injected...

@Inject
private Provider<EntityManager> em;

This is printed onto console:

1) Error in custom provider, java.lang.NullPointerException while locating com.google.inject.persist.jpa.JpaPersistService while locating javax.persistence.EntityManager

On my persistence.xml the persistence-unit is declared as following:

<persistence-unit name="simpleRestApplication">

    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

    <properties>
        <!-- Configuração do driver -->
        <property name="hibernate.dialect"
            value="org.hibernate.dialect.Oracle10gDialect" />
        <property name="hibernate.connection.driver_class"
            value="oracle.jdbc.driver.OracleDriver" />

        <!-- Configuração de conexão -->
        <property name="hibernate.connection.url"
            value="jdbc:oracle:thin:@localhost:1521/XE" />
        <property name="hibernate.connection.username"
            value="system" />
        <property name="hibernate.connection.password"
            value="myPassword123" />
        <property name="hibernate.connection.autocommit"
            value="true" />

        <!-- Configuração do hibernate -->
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.format_sql" value="true" />
        <property name="hibernate.hbm2ddl.auto" value="update" />
        <property name="hibernate.connection.release_mode"
            value="auto" />
        <property name="current_session_context_class"
            value="thread" />
        <property name="hibernate.connection.autoReconnect"
            value="true" />

    </properties>

</persistence-unit>

Solution

  • Based on this link I changed the configure() method on ApplicationModule to install JpaPersistenceModule and start PersistService...

    @Singleton
    private static class JPAInitializer {
        @Inject
        public JPAInitializer(final PersistService service) {
            service.start();
        }
    }
    
    @Override
    protected void configure() {
    
        install(new JpaPersistModule("simpleRestApplication"));
        bind(JPAInitializer.class).asEagerSingleton();
    
        // another bindings...
    
    }
    

    Now the EntityManager is injected without any error...

    public class UserDAOImpl implements UserDAO {
    
        @Inject
        private EntityManager em;
    
    }