Pessoal mais uma vez recorro a vocês para solucionar minhas duvidas de principiante. Tenho visto que minhas transações permanecem abertas e não são reutilizadas, cada vez que o usuário precisa o sistema cria nova transação, ou pelo menos quase sempre, até que o limite estoure e ai eu tenho que parar a aplicação para encerrar as transações e começar novamente para liberar o uso. Minhas duvidas são, eu utilizo Spring Security e sei que o Spring gerencia as transações, eu teria que instalar um novo modulo para utilizar esse gerenciamento? Estou utilizando o c3p0 com timeout configurado em 300, nesse caso não deveria encerrar as transações com mais de 5 minutos? Analisando os códigos abaixo onde esta o erro, devo fechar manualmente toda transação e como fazer isso?
Hibernate cfg
<hibernate-configuration>
<session-factory >
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="connection.datasource">java:/comp/env/jdbc/protocolo</property>
<property name="current_session_context_class">thread</property>
<property name="c3p0.min_size">1</property>
<property name="c3p0.max_size">50</property>
<property name="c3p0.timeout">300</property>
<property name="c3p0.max_statements">50</property>
<property name="c3p0.idle_test_period">3000</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">false</property>
<property name="format_sql">false</property>
<property name="log4j.logger.org.hibernate.type">DEBUG</property>
<mapping class="dominio.Usuario"/>
Context XML
<Resource name="jdbc/protocolo"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://127.0.0.1:5432/protocolo_atendimento?autoReconnect=true"/>
Hibernate Util
[code]public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
@SuppressWarnings("deprecation")
private static SessionFactory buildSessionFactory() {
try {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
return cfg.buildSessionFactory();
} catch (Throwable e) {
System.out.println("Criação inicial do objeto SessionFactory falhou. Erro: " + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}[/code]
Hibernate Filter
[code]
public class ConexaoHibernateFilter implements Filter {
private SessionFactory sf;
@Override
public void init(FilterConfig config) throws ServletException {
this.sf = HibernateUtil.getSessionFactory();
}
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
try {
this.sf.getCurrentSession().beginTransaction();
chain.doFilter(servletRequest, servletResponse);
this.sf.getCurrentSession().getTransaction().commit();
this.sf.getCurrentSession().close();
} catch (Throwable ex) {
try {
if (this.sf.getCurrentSession().getTransaction().isActive()) {
this.sf.getCurrentSession().getTransaction().rollback();
}
} catch (Throwable t) {
t.printStackTrace();
}
throw new ServletException(ex);
}
}
@Override
public void destroy() {
} [/code]
Dao Factory
[code]
@SuppressWarnings(“rawtypes”)
public class DAOFactory {
private static GenericDAOAbstract insantiateDAO(Class daoClass) {
try {
return (GenericDAOAbstract) daoClass.newInstance();
} catch (Exception ex) {
throw new RuntimeException("Não conseguiu instanciar o DAO: "
+ daoClass, ex);
}
}
public static UsuarioDAO getUsuarioDAO() {
return (UsuarioDAO) insantiateDAO(UsuarioDAOImpl.class);
}[/code]
Generic Dao
[code]
public abstract class GenericDAOAbstract<T, ID extends Serializable>
implements GenericDAO<T, ID> {
private Class<T> persistentClass;
private Session session;
@SuppressWarnings("unchecked")
public GenericDAOAbstract() {
this.persistentClass = (Class<T>)
( (ParameterizedType) getClass().getGenericSuperclass() )
.getActualTypeArguments()[0];
}
public void setSession(Session session){
this.session = session;
}
public Session getSession(){
if (session == null){
session = HibernateUtil.getSessionFactory().openSession();
}
return session;
}
public Class<T> getPersistentClass(){
return persistentClass;
}
public void save(T entity) throws DAOException {
getSession().saveOrUpdate(entity);
}
public void delete(T entity) throws DAOException {
getSession().delete(entity);
}
public void flush() throws DAOException {
getSession().flush();
}
public void clear() throws DAOException {
getSession().clear();
}
@SuppressWarnings({ "deprecation", "unchecked" })
public T findByID(ID id, boolean lock) throws DAOException {
T entity;
if (lock){
entity = (T) getSession().load(getPersistentClass(), id, LockMode.UPGRADE);
} else {
entity = (T) getSession().load(getPersistentClass(), id);
}
return entity;
}
@SuppressWarnings("unchecked")
public List<T> findByExample(T exampleInstance, String... excludeProperty) throws DAOException {
Criteria criteria = getSession().createCriteria(getPersistentClass());
Example example = Example.create(exampleInstance);
for (String exclude : excludeProperty) {
example.excludeProperty(exclude);
}
criteria.add(example);
return criteria.list();
}
public List<T> findAll() throws DAOException {
return findByCriteria();
}
@SuppressWarnings("unchecked")
protected List<T> findByCriteria(Criterion... criterion) {
Criteria criteria = getSession().createCriteria(getPersistentClass());
for (Criterion c : criterion) {
criteria.add(c);
}
return criteria.list();
}[/code]
Minha Classe Usuario Service.
[code]
public class UsuarioService {
private UsuarioDAO usuarioDao = DAOFactory.getUsuarioDAO();
public void salvar(Usuario usuario) throws FalhaDeInclusaoException {
try {
usuarioDao.getSession().beginTransaction();
usuarioDao.save(usuario);
usuarioDao.getSession().getTransaction().commit();
} catch (DAOException e) {
e.printStackTrace();
throw new FalhaDeInclusaoException();
}
}[/code]
Meu web.xml esta assim:
<display-name>ProtocoloDeAtendimento</display-name>
<welcome-file-list>
<welcome-file>faces/publico/login.xhtml</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>120</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
<url-pattern>*.xhtml</url-pattern>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<error-page>
<exception-type>
javax.servlet.ServletException
</exception-type>
<location>
/publico/login.xhtml
</location>
</error-page>
<context-param>
<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
<param-value>resources.application</param-value>
</context-param>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
<filter>
<filter-name>conexaoFilter</filter-name>
<filter-class>apresentacao.filter.ConexaoHibernateFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>conexaoFilter</filter-name>
<url-pattern>*.jsf</url-pattern>
<url-pattern>*.xhtml</url-pattern>
<url-pattern>/faces/*</url-pattern>
</filter-mapping>
<resource-ref>
<description>DataSource protocolo</description>
<res-ref-name>jdbc/protocolo</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<resource-ref>
<description>Mail Session</description>
<res-ref-name>mail/Session</res-ref-name>
<res-type>javax.mail.Session</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/applicationContext-security.xml
</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Sei que tem muitas fontes sobre o assunto na internet, mas gostaria de entender onde estou errando, se alguém puder ajudar agradeço, além disso gostaria de saber se esta é a melhor abordagem.