Bom dia galera. Estou usando filtros para fechar a sessao com o hibernate. Mas esta dando um erro que eu nao consigo resolver. Tenho uma listagem de fornecedores que no caso tento excluir um fornecedor que é referenciado como chave externa em outra tabela. Ou seja, vai ter que dar erro de integridade. Violacao de Integridade, porque nao pode apagar um dado que é referenciado em outra tabela. Mas na hora de ver o erro esta acusando um outro erro. Session is close. Mas pelo meu ver nao esta fechado. Vou passar a strackTrace e os codigos para que voces possam me ajudar…
Filtro
public class HibernateFilter implements Filter {
private FilterConfig config;
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
try {
chain.doFilter(req, resp);
} finally {
HibernateUtil.closeSessao();
}
}
public void init(FilterConfig config) throws ServletException {
this.config = config;
}
}
Web.xml (filtro)
<filter>
<filter-name>Hibernate</filter-name>
<filter-class>br.com.MGFSuporte.filtros.HibernateFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Hibernate</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
HibernateUtil
public class HibernateUtil {
private static final SessionFactory factory;
private static final ThreadLocal<Session> threadSession = new ThreadLocal<Session>();
private static final ThreadLocal<Transaction> threadTransaction = new ThreadLocal<Transaction>();
static {
try {
Configuration conf = new Configuration();
conf.configure();
factory = conf.buildSessionFactory();
//new SchemaExport(conf).create(true, true);
} catch (Throwable ex) {
ex.printStackTrace();
throw new ExceptionInInitializerError(ex) ;
}
}
public static Session getSession() {
Session s = (Session) threadSession.get();
try {
if (s == null) {
s = factory.openSession();
threadSession.set(s);
}
} catch (HibernateException h) {
throw h;
}
return s;
}
public static void closeSessao() {
try {
Session session = (Session)threadSession.get();
threadSession.set(null);
if ((session != null) && (session.isOpen())) {
session.close();
}
} catch(HibernateException ex) {
throw ex;
}
}
public static void beginTransacao() {
try {
Transaction transacao = (Transaction)threadTransaction.get();
if (transacao == null) {
transacao = getSession().beginTransaction();
threadTransaction.set(transacao);
}
} catch (HibernateException he) {
throw he;
}
}
public static void comitTransacao() {
Transaction transacao = (Transaction)threadTransaction.get();
try {
if (transacao != null && !transacao.wasCommitted() && !transacao.wasRolledBack())
transacao.commit();
threadTransaction.set(null);
} catch (HibernateException he) {
rollbackTransaction();
throw he;
}
}
public static void rollbackTransaction() {
Transaction transacao = (Transaction)threadTransaction.get();
try {
threadTransaction.set(null);
if (transacao != null && !transacao.wasCommitted() && !transacao.wasRolledBack())
transacao.rollback();
} catch (HibernateException he) {
throw he;
}
}
}
Classe Action que chama o DAO
public class ClienteEditadoAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
ActionErrors errors = new ActionErrors();
DynaValidatorForm dyna = (DynaValidatorForm)form;
if (request.getParameter("operacao").equalsIgnoreCase("Enviar")) {
try {
ClienteDAOHibernate clienteDAO = new ClienteDAOHibernate();
Cliente cliente = new Cliente();
ConvertUtils.register(new StringLong(), java.lang.Long.class);
BeanUtils.copyProperties(cliente, dyna);
clienteDAO.updateCliente(cliente);
HibernateUtil.comitTransacao();
} catch (HibernateException he) {
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.banco"));
saveErrors(request, errors);
he.printStackTrace();
request.setAttribute("erroBanco", he.getMessage());
}
} else {
try {
Cliente cliente = new Cliente();
ClienteDAOHibernate clienteDAO = new ClienteDAOHibernate();
cliente = clienteDAO.consultarPorId(Long.parseLong(dyna.getString("id")));
HibernateUtil.getSession().delete(cliente);
HibernateUtil.comitTransacao();
} catch (HibernateException he) {
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.banco"));
saveErrors(request, errors);
he.printStackTrace();
request.setAttribute("erroBanco", he.getMessage());
}
}
if(!errors.isEmpty()) {
return mapping.findForward("failure");
} else {
return mapping.findForward("success");
}
}
}
O StackTrace…
org.hibernate.SessionException: Session is closed
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:116)
at org.hibernate.transaction.JDBCTransaction.rollbackAndResetAutoCommit(JDBCTransaction.java:183)
at org.hibernate.transaction.JDBCTransaction.rollback(JDBCTransaction.java:162)
at br.com.MGFSuporte.DAO.HibernateUtil.rollbackTransaction(HibernateUtil.java:87)
at br.com.MGFSuporte.DAO.HibernateUtil.comitTransacao(HibernateUtil.java:76)
at br.com.MGFSuporte.controller.ClienteEditadoAction.execute(ClienteEditadoAction.java:54)
at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:304)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at br.com.MGFSuporte.filtros.HibernateFilter.doFilter(HibernateFilter.java:44)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:868)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:663)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
at java.lang.Thread.run(Unknown Source)
Obrigado pela ajuda…