Estou tentando fazer um exemplo de JPA
+ Spring
.
Mas estou com problema ao gerenciar transações.
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="TwsPersistence" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>model.User</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="
true" />
</properties>
</persistence-unit>
</persistence>
applicationContext.xml:
<!-- ANNOTATIONS POUR AOP -->
<aop:aspectj-autoproxy />
<!-- ANNOTATIONS POUR LA CREATION DE BEANS -->
<context:component-scan base-package="com.tws" />
<!-- Datasource -->
<bean name="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url"
value="jdbc:postgresql:/localhost:5432/tecwebsoft" />
<property name="username" value="p" />
<property name="password" value="a" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="TwsPersistence" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="false"/>
<bean id="genericDAO" class="com.tws.persistence.dao.GenericDAO"></bean>
DAO.java:
@PersistenceContext
private EntityManager manager;
@Override
@Transactional(propagation = Propagation.REQUIRED)
public <T> List<T> load(Class<T> classe) {
try {
DetachedCriteria dc = DetachedCriteria.forClass(classe);
// manager.getTransaction().begin();
Session sessao = (Session) manager.getDelegate();
System.out.println("Manager: " + manager);
System.out.println("Sessão: " + sessao);
Criteria criteria = dc.getExecutableCriteria(sessao);
return criteria.list();
} catch (Exception e) {
System.out.println("Falha");
e.printStackTrace();
return null;
}
}
Exception:
Sessão: SessionImpl(<closed>)
org.hibernate.SessionException: Session is closed!
at org.hibernate.impl.AbstractSessionImpl.errorIfClosed(AbstractSessionImpl.java:72)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1688)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347)
at com.tws.persistence.dao.GenericDAO.load(GenericDAO.java:64)
at Main.main(Main.java:30)