Problemas de conexão com o Hibernate

12 respostas
H

Pessoal, estou com um problema no hibernate na conexão com o banco de dados. Estou usando o FireBird 1.0 com o respectivo JDBC. Apesar de já está adicionado todos os .jar do firebird no meu projeto do Eclipse, os coloquei também no CLASSPATH. O arquivo hibernate.properties está na pasta WEB-INF(já tentei colocar ele em outras pastas também). Na hora que vai abrir a conexão com o Banco de Dados, dá a seguinte mensagem de erro:

exception

org.apache.jasper.JasperException: The user must supply a JDBC connection

org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:372)

org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)

org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)

javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1056)

org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:388)

org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:231)

org.apache.struts.action.ActionServlet.process(ActionServlet.java:1164)

org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:415)

javax.servlet.http.HttpServlet.service(HttpServlet.java:709)

javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

root cause

java.lang.UnsupportedOperationException: The user must supply a JDBC connection

net.sf.hibernate.connection.UserSuppliedConnectionProvider.getConnection(UserSuppliedConnectionProvider.java:32)

net.sf.hibernate.impl.BatcherImpl.openConnection(BatcherImpl.java:292)

net.sf.hibernate.impl.SessionImpl.connect(SessionImpl.java:3373)

net.sf.hibernate.impl.SessionImpl.connection(SessionImpl.java:3333)

net.sf.hibernate.impl.BatcherImpl.prepareQueryStatement(BatcherImpl.java:67)

net.sf.hibernate.loader.Loader.prepareQueryStatement(Loader.java:784)

net.sf.hibernate.loader.Loader.doQuery(Loader.java:269)

net.sf.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:138)

net.sf.hibernate.loader.Loader.doList(Loader.java:1063)

net.sf.hibernate.loader.Loader.list(Loader.java:1054)

net.sf.hibernate.hql.QueryTranslator.list(QueryTranslator.java:854)

net.sf.hibernate.impl.SessionImpl.find(SessionImpl.java:1554)

net.sf.hibernate.impl.QueryImpl.list(QueryImpl.java:49)

bd.DdocService.getDdocList(DdocService.java:209)

org.apache.jsp.pages.respostapesquisa_jsp._jspService(respostapesquisa_jsp.java:122)

org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)

javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)

org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)

org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)

javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1056)

org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:388)

org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:231)

org.apache.struts.action.ActionServlet.process(ActionServlet.java:1164)

org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:415)

javax.servlet.http.HttpServlet.service(HttpServlet.java:709)

javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

alguém sabe o que pode estar acontecendo?

Obrigado por qualquer ajuda.

Herlen

12 Respostas

_fs

Pode postar o seu hibernate.properties? Se sim, não se esqueça de retirar o password do banco.

H

Aí vai:

FireBird

hibernate.dialect cirrus.hibernate.sql.InterbaseDialect
hibernate.connection.driver_class org.firebirdsql.jdbc.FBDriver
hibernate.connection.url jdbc:firebirdsql:localhost/3050:D:/Dados/Interbase/Inei/ALIBDBS1
hibernate.connection.username meuusuario
hibernate.connection.password minhasenha

ricardolecheta

o pacote mudou nas novas versões (faz tempo)…

não é cirrus.hibernate, é net.sf.hibernate :slight_smile:

H

ricardolecheta:
o pacote mudou nas novas versões (faz tempo)…

não é cirrus.hibernate, é net.sf.hibernate :-)

Fiz a mudança de cirrus.hibernate para net.sf.hibernate mas não deu certo.
Apenas para verificar se ele está pegando do lugar certo, renomeei o arquivo hibernate.properties para hibernate.properties2 e adivinha… o mesmo erro aconteceu. Ou seja, não é daí que ele está pegando essas informações. No projeto só tem esse arquivo nesse diretório chamado hibernate.properties.
Outra coisa, na linha
Session s = sessionFactory.openSession();
se eu der um “Step Into”, debugando, abre uma janela “Class File Editor” onde diz o seguinte:
“The source attachment does not contain the source for the file SessionFactoryImpl.class”
Dando a opção “Change attached resource”.

Será que é aí a origem do problema?

_fs

Este erro indica que você não tem o código fonte da classe, então não há como debugá-la linha a linha.

Você está fazendo assim:

Configuration conf = new Configuration(); factory = conf.configure().buildSessionFactory(); Session session = factory.openSession();
?

H

LIPE:
Este erro indica que você não tem o código fonte da classe, então não há como debugá-la linha a linha.

Você está fazendo assim:

Configuration conf = new Configuration(); factory = conf.configure().buildSessionFactory(); Session session = factory.openSession();
?

Eu estava fazendo assim:

Configuration cfg = new Configuration().addClass(dto.Ddoc.class);

sessionFactory = cfg.buildSessionFactory();

Session s = sessionFactory.openSession();

Mudei o cfg.buildSessionFactory() para cfg.configure().buildSessionFactory() e dá o erro abaixo:
org.apache.jasper.JasperException: net.sf.hibernate.HibernateException: /hibernate.cfg.xml not found

na linha sessionFactory = cfg.configure().buildSessionFactory();

ricardolecheta

e o hibernate.properties está no classpath?

H

Sim.

H

Olha aí o código completo:

classe DdocService:

public List getDdocList()

{

Session session = ConnectionFactory.getInstance().getSession();
try
            {
                    Query query = session.createQuery("select ddoc from dto.Ddoc ddoc order by ddoc.titulo");
                    return query.list();

            }
            catch (HibernateException e)
            {
                    System.err.println("Hibernate Exception" + e.getMessage());
                    throw new RuntimeException(e);
            }
            finally
            {
                    if (session != null)
                    {
                            try
                            {
                                    session.close();
                            }
                            catch (HibernateException e)
                            {
                                    System.err.println("Hibernate Exception" + e.getMessage());
                                    throw new RuntimeException(e);
                            }

                    }
            }
    }

Classe ConnectionFactory:

private ConnectionFactory()

{

try

{
Configuration cfg = new Configuration().addClass(dto.Ddoc.class);

                    sessionFactory = cfg.buildSessionFactory();

// sessionFactory = cfg.configure().buildSessionFactory();

}
            catch (MappingException e)
            {
                    System.err.println("Mapping Exception" + e.getMessage());
                    throw new RuntimeException(e);
            }
            catch (HibernateException e)
            {
                    System.err.println("Hibernate Exception" + e.getMessage());
                    throw new RuntimeException(e);
            }

    }
    
    
    public static synchronized ConnectionFactory getInstance()
    {
            if (instance == null)
            {
                    instance = new ConnectionFactory();
            }
            return instance;
    }

    public Session getSession()
    {
            try
            {
                    Session s = sessionFactory.openSession();
                    return s;
            }
            catch (HibernateException e)
            {
                    System.err.println("Hibernate Exception" + e.getMessage());
                    throw new RuntimeException(e);
            }
    }
H

Com a classe da maneira que está declarada acima, se eu for debugando dando “Step Over”, vai sem dar erro até o finally depois de “return query.list();” executa o finally normalmente, quando chega no final ele volta para o começo do finally e abre uma tela com a seguinte mensagem, não sei se isso tem a ver com a conexão:
Source not found for respostapesquisa_jsp._jspService(HttpServletRequest, HttpServletResponse) line: 53

_fs

Nunca testei sem, mas não está falantando o cfg.configure()?

Dicas:

  • quando for postar código, coloque-o entre as tags [ code]seucodigo[ /code], assim ele fica endentado.
  • já que não está usando log, não faça isso
    System.err.println(“Mapping Exception” + e.getMessage());
    mas sim
    e.printStackTrace();
H
LIPE:
Nunca testei sem, mas não está falantando o cfg.configure()?

Dicas:
- quando for postar código, coloque-o entre as tags [ code]seucodigo[ /code], assim ele fica endentado.
- já que não está usando log, não faça isso
System.err.println("Mapping Exception" + e.getMessage());
mas sim
e.printStackTrace();

Valeu pelas dicas, consegui fazer se conectar... Agora tá dando o erro, vc já viu isso?

Estou usando o struts 1.2.4

javax.servlet.jsp.JspException: Cannot find message resources under key org.apache.struts.action.MESSAGE
org.apache.struts.taglib.TagUtils.retrieveMessageResources(TagUtils.java:1233)
org.apache.struts.taglib.TagUtils.message(TagUtils.java:1082)
org.apache.struts.taglib.TagUtils.message(TagUtils.java:1057)
org.apache.struts.taglib.bean.WriteTag.retrieveFormatString(WriteTag.java:256)
org.apache.struts.taglib.bean.WriteTag.formatValue(WriteTag.java:326)
org.apache.struts.taglib.bean.WriteTag.doStartTag(WriteTag.java:234)
org.apache.jsp.pages.respostapesquisa_jsp._jspx_meth_bean_write_0(respostapesquisa_jsp.java:241)
org.apache.jsp.pages.respostapesquisa_jsp._jspService(respostapesquisa_jsp.java:151)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1056)
org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:388)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:231)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1164)
org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:415)
javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

Olha meus arquivos

respostapesquisa.jsp

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>

<%@ page import="bd.DdocService" %>
<%@ page import="dto.Ddoc" %>
<%@ page import="java.util.List" %>

<html:html locale="true">
<head>
<title>Example 1</title>
<html:base/>
</head>
<body bgcolor="white">

<h3>Example 1</h3>
<html:errors />

<%
   /*
    * This code will generate a list of objects from the
    * database and place a reference to this list in the
    * request object.
    *
    */
        List DdocList = DdocService.getInstance().getDdocList();
        request.setAttribute("Ddocs", DdocList);
%>
<p>List of Ddocs in <code>Ddoc</code> table of database <code>test</code>.</p>
<table border=1>
<!-- This code will iterate over the list of Ddocs, creating a table
        row for each Ddoc. -->
<logic:iterate id="element" name="Ddocs" scope="request" type="dto.Ddoc" >
<tr>
   <td><bean:write name="element" property="id" /></td>
        <td><bean:write name="element" property="titulo" /></td>
</tr>
</logic:iterate>
</table>
<p>Sumbit to add an Ddoc:</p>

<!-- This form will post the submitted data to the addDdoc Action Mapping -->
<html:form action="pesquisa.jsp" method="post">
<table border=1>
<tr><td>name:</td><td><html:text property="id" /></td>
<td>description:</td><td><html:text property="titulo" /></td></tr>
</table><br/>
<html:submit />
</html:form>
</body>
</html:html>

web.xml:

?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
  PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
  "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
  <display-name>Starways</display-name>
  
  <!-- Standard Action Servlet Configuration (with debugging) -->
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>2</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>2</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>


  <!-- Standard Action Servlet Mapping -->
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>


  <!-- The Usual Welcome File List -->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>


  <!-- Struts Tag Library Descriptors -->
  <taglib>
    <taglib-uri>/tags/struts-bean</taglib-uri>
    <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-html</taglib-uri>
    <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-logic</taglib-uri>
    <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-nested</taglib-uri>
    <taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-tiles</taglib-uri>
    <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
  </taglib>

</web-app>

Valeu pela ajuda,
Herlen

Criado 22 de março de 2005
Ultima resposta 23 de mar. de 2005
Respostas 12
Participantes 3