Problema em injetar EntityManager no DAO

2 respostas
marcosvidolin

Olá galera,

Tenho um projeto Maven rodando no Glassfish 3.1, utilizo os framewroks: Spring 3, JSF 2 e Hibernate/JPA.
Ao tentar subir o projeto no Glassfish obtenho o seguinte erro:

[#|2011-12-14T20:25:11.493-0200|INFO|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=17;_ThreadName=Thread-2;|2011-12-14 20:25:11,483 [admin-thread-pool-4848(2)] ERROR org.springframework.web.context.ContextLoader - Context initialization failed  
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'caixaDao' defined in file [C:\glassfish3\glassfish\domains\domain1\eclipseApps\arquivista\WEB-INF\classes\br\com\arquivista\persistence\dao\jpa\CaixaDao.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [javax.persistence.EntityManagerFactory]: : Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/spring/spring-persistence.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: Default] Unable to build EntityManagerFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/spring/spring-persistence.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: Default] Unable to build EntityManagerFactory  
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:730)  
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:196)  
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003)  
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907)  
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)  
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)  
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)  
...

Por algum motivo o Spring não consegue criar o bean "entityManagerFactory". Alguém pode me dar uma mãozinha, por favor?
Estes são os arquivos de configuração:

spring-persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util" xmlns:jee="http://www.springframework.org/schema/jee"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd"
	default-autowire="constructor">

	<!-- Inicializa os beans com anotacoes: @Component, @Service e @Controller -->
	<context:component-scan base-package="br.com.arquivista.persistence.dao.jpa" />

	<!-- Processa as anotacoes: @Scope, @Autowired, @Required e @PersistenceContext -->
	<context:annotation-config />

	<!-- Interpretador de anotacoes @Transactional -->
	<tx:annotation-driven transaction-manager="txManager" />

	<!-- Carrega propriedades do arquivo 'database.properties' -->
	<context:property-placeholder location="/WEB-INF/database.properties" />

	<!-- Gerenciador de transacoes Spring baseado em JPA -->
	<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>

	<!-- Fabrica de EntityManager do JPA para persistencia -->
	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="dataSource" ref="myDataSource" />
		<property name="loadTimeWeaver">
			<bean
				class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
		</property>
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<property name="showSql" value="${jpa.show.sql}" />
				<property name="generateDdl" value="${jpa.generate.ddl}" />
				<property name="database" value="${jpa.database}" />
			</bean>
		</property>
		<property name="jpaProperties">
			<props>
				<prop key="hibernate.dialect">${jpa.dialect}</prop>
			</props>
		</property>
	</bean>

	<!-- Datasource JDBC para o banco de dados -->
	<import resource="spring-datasource.xml" />

</beans>
database.properties
#  
# Configuracoes do banco de dados  
#  
db.driverClassName=com.mysql.jdbc.Driver  
db.hostname=localhost  
db.database=arquivista  
db.username=root  
db.password=root  
db.port=3306  
db.url=jdbc:mysql://${db.hostname}:${db.port}/${db.database}  
  
#  
# Configuracoes Hibernate/JPA  
#  
jpa.dialect=org.hibernate.dialect.MySQLInnoDBDialect  
jpa.database=MYSQL  
jpa.show.sql=true  
jpa.generate.ddl=false
spring-datasource.xml
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"  
    xmlns:util="http://www.springframework.org/schema/util" xmlns:jee="http://www.springframework.org/schema/jee"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd  
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd  
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd">  
  
    <!-- Carrega propriedades do arquivo 'database.properties' -->  
    <context:property-placeholder location="/WEB-INF/database.properties" />  
  
    <!-- Datasource JDBC para o banco de dados -->  
    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"  
        destroy-method="close">  
        <property name="driverClassName" value="${db.driverClassName}" />  
        <property name="url" value="${db.url}" />  
        <property name="username" value="${db.username}" />  
        <property name="password" value="${db.password}" />  
    </bean>  
  
</beans>
CaixaDao.java
@Repository  
    public class CaixaDao extends AbstractDao<Integer, Caixa> implements ICaixaDao {  
      
        /** 
         * Construtor padrão. 
         *  
         * @param factory 
         *          do tipo da entidade 
         */  
        @Autowired  
        public CaixaDao(  
            @Qualifier("entityManagerFactory") final EntityManagerFactory factory) {  
            super(factory, Caixa.class);  
        }  
      
        /** 
         * Busca todas as Caixas 
         *  
         * @return retorna uma lista de {@link Caixa} 
         */  
        @Override  
        @SuppressWarnings("unchecked")  
        public List<Caixa> findAll() {  
            List<Caixa> result = getJpaTemplate().findByNamedQuery(Caixa.FIND_ALL);  
      
            if (!result.isEmpty()) {  
                return result;  
            }  
      
            return null;  
        }  
      
    }
AbstractDao
public abstract class AbstractDao<K, E> extends JpaDaoSupport implements  
            IAbstractDao<K, E> {  
      
        private Class<E> entityClass;  
      
        public AbstractDao(final EntityManagerFactory factory,  
                final Class<E> entityClass) {  
            setEntityManagerFactory(factory);  
            this.entityClass = entityClass;  
        }  
      
        public E findById(final K id) {  
            return (E) getJpaTemplate().find(entityClass, id);  
        }  
      
        public void remove(final E entity) {  
            getJpaTemplate().remove(entity);  
        }  
      
        public void removeChild(final Object entity) {  
            getJpaTemplate().remove(entity);  
        }  
          
        ...  
          
    }

Obrigado pessoal
[]'s

2 Respostas

marcosvidolin

Olá pessoal,

será que tem algo a ver com meu persistence.xml?

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
	xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
	<persistence-unit name="Default">
	</persistence-unit>

</persistence>
pois o log gerado é esse:
cannot Deploy arquivista
Deployment Error for module: arquivista: Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'txManager' defined in ServletContext resource [/WEB-INF/spring/spring-persistence.xml]: Cannot resolve reference to bean 'entityManagerFactory' while setting bean property 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/spring/spring-persistence.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: Default] Unable to build EntityManagerFactory. Please see server.log for more details.

Obrigado.

thimor
marcosvidolin:
Olá pessoal,

será que tem algo a ver com meu persistence.xml?

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
	xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
	<persistence-unit name="Default">
	</persistence-unit>

</persistence>
pois o log gerado é esse:
cannot Deploy arquivista
Deployment Error for module: arquivista: Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'txManager' defined in ServletContext resource [/WEB-INF/spring/spring-persistence.xml]: Cannot resolve reference to bean 'entityManagerFactory' while setting bean property 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/spring/spring-persistence.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: Default] Unable to build EntityManagerFactory. Please see server.log for more details.

Obrigado.

voce nao criou o datasource no seu arquivo de configuracao do spring. Se for usar persistence.xml basta declarar assim:

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter"
			p:databasePlatform="${jpa.databasePlatform}" p:showSql="${jpa.showSql}"/>
        </property>
</bean>
caso queira usar o datasource vai precisar declarar um datasource:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
			p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" p:username="${jdbc.username}"
			p:password="${jdbc.password}"/>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
			p:dataSource-ref="dataSource">
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter"
			p:databasePlatform="${jpa.databasePlatform}" p:showSql="${jpa.showSql}"/>
        </property>
    </bean>
Criado 15 de dezembro de 2011
Ultima resposta 27 de dez. de 2011
Respostas 2
Participantes 2