Spring + JPA

3 respostas
andremion

Alguém sabe qual o motivo do meu entityManager não está sendo injetado nos meus DAOs?
Ele sempre vem null.
Eu estou executando o JUnit.

Segue meus arquivos.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/applicationContext.xml"}, loader = MockServletContextWebContextLoader.class)
public class Tests extends TestCase {

    @Autowired
    private ApplicationContext applicationContext;
...

MockServletContextWebContextLoader.java

public class MockServletContextWebContextLoader extends AbstractContextLoader {

    public final ConfigurableApplicationContext loadContext(String... locations) throws Exception {
        ConfigurableWebApplicationContext context = new XmlWebApplicationContext();
        context.setServletContext(new MockServletContext("/webapp", new FileSystemResourceLoader()));
        context.setConfigLocations(locations);
        context.refresh();
        AnnotationConfigUtils.registerAnnotationConfigProcessors((BeanDefinitionRegistry) context.getBeanFactory());
        context.registerShutdownHook();
        return context;
    }

    protected String getResourceSuffix() {
        return "-context.xml";
    }

}

applicationContext.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
       http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">
    
    <!-- Arquivo de configurações da aplicação -->
    <context:property-placeholder location="classpath:application.properties" />

    <!-- Ativa annotations nas classes -->
    <context:annotation-config/>
    
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="application"/>
    </bean>
    
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="DBSisHairPostgreSQLHibernate"/>
    </bean>
    
    <!-- JPA annotations bean post processor -->
    <!-- <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/> -->
    
    <!-- Exception translation bean post processor -->
    <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
    
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>
    
    <tx:annotation-driven transaction-manager="transactionManager"/>
    
    <!-- Configuração das transações -->
    <tx:advice id="transactionAdvice">
        <!-- Configurações de transação -->
        <tx:attributes>
            <!-- Todos os métodos que começam com "select" são read-only -->
            <tx:method name="select*" propagation="SUPPORTS" read-only="true" rollback-for="java.lang.Exception"/>
            <!-- Os outros métodos requerem transação -->
            <tx:method name="*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
        </tx:attributes>
    </tx:advice>
    
    <!-- Local onde a configuração de transação será aplicada -->
    <aop:config>
        <!-- Intercepterá todos os métodos públicos de classes/subclasses desse pacote -->
        <aop:advisor pointcut="execution(public * facade.*.*(..))" advice-ref="transactionAdvice"/>
    </aop:config>
    
    <bean id="daoFactory" class="dao.DaoFactory" factory-method="getDaoFactory">
        <constructor-arg><value>${factoryClass}</value></constructor-arg>
    </bean>

    <bean id="cadastros" class="bo.Cadastros"/>
    
</beans>

JpaGenericDao.java

@Repository
public abstract class JpaGenericDao<Entity, Id extends Serializable> {
    
    @PersistenceContext
    protected EntityManager entityManager;
    
    protected Class<Entity> entityClass;
    
    public JpaGenericDao() {
        this.entityClass = (Class<Entity>) ((ParameterizedType) getClass().getGenericSuperclass())
                .getActualTypeArguments()[0];
    }
    
    public void insert(Entity instance) throws DaoException {
        try {
            this.entityManager.persist(instance);
        } catch (RuntimeException e) {
            throw new DaoException(e);
        }
    }
...

3 Respostas

idev4web

tente declarar assim seu entity manager













idev4web

Pode ser tambem que voce tenha que marcar as interfaces dos DAO com a anotaçao

@transaction

andremion

Não funcionou!

Tem uma linha no Console assim:

[org.springframework.context.support.GenericApplicationContext]- Bean ‘entityManagerFactory’ is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

Acho que isso tem a ver com o meu problema, só não sei como resolver

Criado 15 de julho de 2009
Ultima resposta 16 de jul. de 2009
Respostas 3
Participantes 2