Hibernate does not return data

Asked

Viewed 84 times

3

I am developing an application to learn, and when trying to access the application (JSF) Hibernate does not return data. Have any idea?

Follow my class Filter:

package br.com.importacao.filters;

import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;



/***
 * ESSE FILTER VAI SER CHAMADO TODA VEZ QUE FOR REALIZADO 
 * UMA REQUISIÇÃO PARA O FACES SERVLET.
 * */


@WebFilter(servletNames = {"Faces Servlet"})
public class JPAFilter implements Filter{

    private EntityManagerFactory entityManagerFactory;

    private String persistence_unit_name = "unit_app";

    public  JPAFilter() {

    }

    public void destroy() {
        this.entityManagerFactory.close();
    } 

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {


        //CRIANDO UM ENTITYMANAGER
        EntityManager entityManager = this.entityManagerFactory.createEntityManager();

        //ADICIONANDO ELE NA REQUISIÇÃO
        req.setAttribute("entityManager", entityManager);

        //INICIANDO UMA TRANSAÇÃO
        entityManager.getTransaction().begin();

        //INICIANDO FACES SERVLET
        chain.doFilter(req, resp);

        try {
            //SE NÃO TIVER ERRO NA OPERAÇÃO ELE EXECUTA O COMMIT
            entityManager.getTransaction().commit();

        } catch (Exception e) {
            //SE TIVER ERRO NA OPERAÇÃO É EXECUTADO O rollback
            entityManager.getTransaction().rollback();
        } finally {

            entityManager.close();

        }
    }

    public void init(FilterConfig fConfig) throws ServletException {

        //CRIA O entityManagerFactory COM OS PARÂMETROS DEFINIDOS NO persistence.xml
        this.entityManagerFactory = Persistence.createEntityManagerFactory(this.persistence_unit_name);

    }

}

Authentication class:

package br.com.importacao.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.importacao.model.UsuarioModel;

@WebFilter("/sistema/*")
public class AutenticacaoFilter implements Filter {

    @Override
    public void destroy() {     
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpSession         httpSession         = ((HttpServletRequest) request).getSession();
        HttpServletRequest  httpServletRequest  =(HttpServletRequest)  request;
        HttpServletResponse httpServletResponse =(HttpServletResponse) response;

        if(httpServletRequest.getRequestURI().indexOf("index.xhtml") <= -1) {

            UsuarioModel usuarioModel = (UsuarioModel) httpSession.getAttribute("Usuário Autenticado");
            if (usuarioModel == null) {
                httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+ "/index.xhtml");
            } 
            else {
                    chain.doFilter(request, response);
            }
        }
        else {
            chain.doFilter(request, response);
        }

    }

    @Override
    public void init(FilterConfig fConfig) throws ServletException {        
    }

}

Persistence file:

<persistence 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"
             version="2.0">

    <persistence-unit name="unit_app" transaction-type="RESOURCE_LOCAL">
        <description>
            ARQUIVO DE PERSISTÊNCIA JPA E HIBERNATE            
        </description>
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>        
            <property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://127.0.0.1\SQL2014:1433;dataBaseName=Aplicacao" />
            <property name="javax.persistence.jdbc.user" value="sa" />
            <property name="javax.persistence.jdbc.password" value="sql2014" />


            <property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hibernate.format_sql" value="true" />
        </properties>
    </persistence-unit>
</persistence>

And the log after trying to log into the application:

INFO: HHH000204: Processing Persistenceunitinfo [ name: unit_app ...] Sep 10, 2018 11:58:14 PM org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {4.3.0.Final} Sep 10, 2018 11:58:14 PM org.hibernate.cfg.Environment INFO: HHH000206: Hibernate.properties not found Sep 10, 2018 11:58:14 pm org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode Provider name : javassist Sep 10, 2018 11:58:16 PM org.hibernate.Annotations.common.Reflection.java.Javareflectionmanager INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final} Sep 10, 2018 11:58:16 PM org.hibernate.engine.jdbc.Connections.internal.Drivermanagerconnectionproviderimpl configure INFO: HHH000402: Using Hibernate built-in Connection pool (not for Production use!) Sep 10, 2018 11:58:16 PM org.hibernate.engine.jdbc.Connections.internal.Drivermanagerconnectionproviderimpl buildCreator INFO: HHH000401: using driver [com.microsoft.sqlserver.jdbc.Sqlserverdriver] at URL [jdbc:sqlserver:/127.0.0.1 SQL2014:1433;dataBaseName=Application] set 10, 2018 11:58:16 pm org.hibernate.engine.jdbc.Connections.internal.Drivermanagerconnectionproviderimpl buildCreator INFO: HHH000046: Connection properties: {user=sa, password=***} Sep 10, 2018 11:58:16 pm org.hibernate.engine.jdbc.Connections.internal.Drivermanagerconnectionproviderimpl buildCreator INFO: HHH000006: Autocommit mode: false Sep 10, 2018 11:58:16 PM org.hibernate.engine.jdbc.Connections.internal.Drivermanagerconnectionproviderimpl configure INFO: HHH000115: Hibernate Connection pool size: 20 (min=1) Sep 10, 2018 11:58:27 pm org.hibernate.dialect.Dialect INFO: HHH000400: Using dialect: org.hibernate.dialect.Sqlserverdialect set 10, 2018 11:58:30 pm org.hibernate.hql.internal.Ast.Astquerytranslatorfactory INFO: HHH000397: Using Astquerytranslatorfactory Sep 10, 2018 11:58:36 PM org.hibernate.tool.hbm2ddl.Schemaupdate execute INFO: HHH000228: Running hbm2ddl schema update Sep 10, 2018 11:58:36 PM org.hibernate.tool.hbm2ddl.Schemaupdate execute INFO: HHH000102: Fetching database Metadata Sep 10, 2018 11:58:37 PM org.hibernate.tool.hbm2ddl.Schemaupdate execute INFO: HHH000396: Updating schema Sep 10, 2018 11:58:45 PM org.hibernate.tool.hbm2ddl.Tablemetadata INFO: HHH000261: Table found: Application.dbo.tbPessoa Sep 10, 2018 11:58:45 PM org.hibernate.tool.hbm2ddl.Tablemetadata INFO: HHH000037: Columns: [id_usuario_cadastro, id_pessoa, id_usuario, fl_sexo, nm_pessoa, dt_cadastro, ds_email, fl_origemcadastro, ds_endereco] set 10, 2018 11:58:45 PM org.hibernate.tool.hbm2ddl.Tablemetadata INFO: HHH000108: Foreign Keys: [fk_tbusuario_idusuario, fk_6f0fndvdml1p57xaedm3x9hn] Sep 10, 2018 11:58:45 PM org.hibernate.tool.hbm2ddl.Tablemetadata INFO: HHH000126: Indexes: [pk_tbpessoa_idpessoa] Sep 10, 2018 11:58:45 PM org.hibernate.tool.hbm2ddl.Tablemetadata INFO: HHH000261: Table found: Application.dbo.tbUsuario Sep 10, 2018 11:58:45 PM org.hibernate.tool.hbm2ddl.Tablemetadata INFO: HHH000037: Columns: [id_usuario, ds_password, ds_login] Sep 10, 2018 11:58:45 PM org.hibernate.tool.hbm2ddl.Tablemetadata INFO: HHH000108: Foreign Keys: [] Sep 10, 2018 11:58:45 PM org.hibernate.tool.hbm2ddl.Tablemetadata INFO: HHH000126: Indexes: [pk_tbusuario_idusuario] Sep 10, 2018 11:58:45 PM org.hibernate.tool.hbm2ddl.Schemaupdate execute INFO: HHH000232: Schema update complete Sep 10, 2018 11:58:47 PM org.apache.Talina.startup.Hostconfig deployDirectory INFORMATION: Deploying web application directory C: Servers apache-Tomcat-8.0.53 webapps Docs Sep 10, 2018 11:58:52 PM org.apache.Jasper.servlet.Tldscanner scanJars INFORMATION: At least one JAR was Scanned for Tlds yet contained no Tlds. Enable debug logging for this logger for a complete list of Jars that Were Scanned but no Tlds Were found in them. Skipping unneeded Jars During Scanning can improve startup time and JSP Compilation time. Sep 10, 2018 11:58:52 pm org.apache.Catalina.startup.Hostconfig deployDirectory INFO: Deployment of web application directory C: Servers apache-Tomcat-8.0.53 webapps Docs has finished in 5,451 ms Sep 10, 2018 11:58:52 PM org.apache.Talina.startup.Hostconfig deployDirectory INFORMATION: Deploying web application directory C: Servers apache-Tomcat-8.0.53 webapps examples Sep 10, 2018 11:59:05 PM org.apache.Jasper.servlet.Tldscanner scanJars INFORMATION: At least one JAR was Scanned for Tlds yet contained no Tlds. Enable debug logging for this logger for a complete list of Jars that Were Scanned but no Tlds Were found in them. Skipping unneeded Jars During Scanning can improve startup time and JSP Compilation time. Sep 10, 2018 11:59:05 PM org.apache.Applicationcontext log INFORMATION: Contextlistener: contextInitialized() Sep 10, 2018 11:59:05 PM org.apache.Applicationcontext log INFORMATION: Sessionlistener: contextInitialized() Sep 10, 2018 11:59:05 PM org.apache.Applicationcontext log INFORMATION: Contextlistener: attributeAdded('Stockticker', async. Stockticker@1d0af75') Sep 10, 2018 11:59:05 PM org.apache.Talina.startup.Hostconfig deployDirectory INFORMATION: Deployment of web application directory C: Servers apache-Tomcat-8.0.53 webapps examples has finished in 12,551 ms Sep 10, 2018 11:59:05 pm org.apache.Talina.startup.Hostconfig deployDirectory INFORMATION: Deploying web application directory C: Servers apache-Tomcat-8.0.53 webapps host-manager Sep 10, 2018 11:59:10 PM org.apache.Jasper.servlet.Tldscanner scanJars INFORMATION: At least one JAR was Scanned for Tlds yet contained no Tlds. Enable debug logging for this logger for a complete list of Jars that Were Scanned but no Tlds Were found in them. Skipping unneeded Jars During Scanning can improve startup time and JSP Compilation time. set 10, 2018 11:59:10 PM org.apache.Talina.startup.Hostconfig deployDirectory INFORMATION: Deployment of web application directory C: Servers apache-Tomcat-8.0.53 webapps host-manager has finished in 4,901 ms Sep 10, 2018 11:59:10 pm org.apache.Talina.startup.Hostconfig deployDirectory INFORMATION: Deploying web application directory C: Servers apache-Tomcat-8.0.53 webapps manager Sep 10, 2018 11:59:18 PM org.apache.Jasper.servlet.Tldscanner scanJars INFORMATION: At least one JAR was Scanned for Tlds yet contained no Tlds. Enable debug logging for this logger for a complete list of Jars that Were Scanned but no Tlds Were found in them. Skipping unneeded Jars During Scanning can improve startup time and JSP Compilation time. Sep 10, 2018 11:59:18 PM org.apache.Talina.startup.Hostconfig deployDirectory INFO: Deployment of web application directory C: Servers apache-Tomcat-8.0.53 webapps manager has finished in 8.092 ms Sep 10, 2018 11:59:18 pm org.apache.Talina.startup.Hostconfig deployDirectory INFORMATION: Deploying web application directory C: Servers apache-Tomcat-8.0.53 webapps ROOT Sep 10, 2018 11:59:24 PM org.apache.Jasper.servlet.Tldscanner scanJars INFORMATION: At least one JAR was Scanned for Tlds yet contained no Tlds. Enable debug logging for this logger for a complete list of Jars that Were Scanned but no Tlds Were found in them. Skipping unneeded Jars During Scanning can improve startup time and JSP Compilation time. Sep 10, 2018 11:59:24 PM org.apache.Catalina.startup.Hostconfig deployDirectory INFO: Deployment of web application directory C: Servers apache-Tomcat-8.0.53 webapps ROOT has finished in 5,672 ms Sep 10, 2018 11:59:24 pm org.apache.Coyote.Abstractprotocol start INFORMATION:

Hibernate:

    select
        usuarioent0_.id_usuario as id_usuar1_1_,
        usuarioent0_.ds_senha as ds_senha2_1_,
        usuarioent0_.ds_login as ds_login3_1_ 
    from
        tbUsuario usuarioent0_ 
    where
        usuarioent0_.ds_login=? 
        and usuarioent0_.ds_senha=?
  • Places your JSF page too

  • I managed to. But thank you.

  • @Pereira share the solution with us :). You can answer your own question

  • The problem was in the definition: User model userModel = (User model) httpSession.getattribute("Authenticated User"); the correct User model was User model Model = (User model) httpSession.getattribute("user");

1 answer

1

I managed to solve the problem, was in the definition:

UsuarioModel usuarioModel = (UsuarioModel) httpSession.getAttribute("Usuário Autenticado");                                                                     

The right one was:

UsuarioModel usuarioModel = (UsuarioModel) httpSession.getAttribute("usuarioAutenticado");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.