Erro no projeto com hibernate

5 respostas
mirrah

Bom gente, eu estou fazendo um projeto em java para o final do meu curso de T.I. . Nesse, estou querendo usar o hibernate, na verdade estou meio que usando. Na primeira parte do projeto eu tenho que pegar algumas informações que o aluno vai por no sistema através de um servlet, depois enviar para uma classe chamada AlunoDAO que vai ser nela que o hibernate vai acontecer (ou mais ou menos isso) Ai é que tá, quando eu executo a aplicação não me aparece erro nenhum, mas também não aparece o que tinha que aparecer no banco de dados.Será que alguém poderia me dar uma força para encontrar este erro por favor?

vou por o JSP só por desencargo de consciência:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h3>Login</h3>
        <form action="inserirAluServlet" method="POST">
            matricula aluno:<br/>
            <input type="text" name="matricula" value="" /><br/>
            nome:<br/>
            <input type="text" name="nome" value="" /><br/>
            cpf<br/>
            <input type="text" name="cpf" value="" /><br/>
            email:<br/>
            <input type="text" name="email" value="" /><br/>
            senha:<br/>
            <input type="password" name="senha" value="" /><br/>
            newsletter:<br/>
            <input type="radio" name="" value="" /><br/>
            
            <input type="submit" value="Enviar" name="enviar" />
            
        </form>
    </body>
</html>
Agora é o servlet:
package br.com.infoteca.controller;

import br.infoteca.model.dao.AlunoDAO;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class inserirAluServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            
            //obtem os valores das variavéis
            String matriculas = request.getParameter("matricula");
            String nome = request.getParameter("nome");
            String email = request.getParameter("email");
            String cpfs = request.getParameter("cpf");
            String senha = request.getParameter("senha");
            String newsletters = request.getParameter("newsletter");
            
            //converte alguns valores
            int matricula = Integer.parseInt(matriculas);
            int cpf = Integer.parseInt(cpfs);
            int newsletter = Integer.parseInt(newsletters);
            
            //insere as informações no banco de dados
            AlunoDAO.inserirAlu(matricula, nome, email, cpf,
                    senha, newsletter);
            
        }catch( Exception e )
        {
            System.out.println("Houve uma exceção" + e);
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
Eu sei que esse DAO nesta classe está errado, vi isso agora, já vou consertar isso rsrsrs:
package br.infoteca.model.dao;

import br.infoteca.model.beans.Aluno;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class AlunoDAO {
    
    public static void inserirAlu(int matricula, String nome, String email, 
            int cpf, String senha, int newsletter)
    {
        try
        {
            
            SessionFactory sesfac = new Configuration().configure().buildSessionFactory();
            Session session = sesfac.openSession();
            Aluno aluno = new Aluno();
            aluno.setMatricula(matricula);
            aluno.setNome(nome);
            aluno.setEmail(email);
            aluno.setCpf(cpf);
            aluno.setSenha(senha);
            aluno.setNewsletter(newsletter);
            
            Transaction transaction = session.beginTransaction();
            session.save(aluno);
            transaction.commit();
            session.close();
            
            
        }catch( Exception exc )
        {
        }
        
        
    }
    
}
Agora o XML de configuração do hibernate:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">25quadrado</property>
    <mapping resource="br/infoteca/model/frameworks/Aluno.hbm.xml"/>
    <mapping resource="br/infoteca/model/frameworks/Endereco.hbm.xml"/>
  </session-factory>
</hibernate-configuration>
Agora o mapeamento da classe Aluno:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="br.infoteca.model.beans.Aluno" table="aluno"/>
  <id name="matricula" column="matriculaAlu"/>
  <property name="nome"/>
  <property name="email"/>
  <property name="cpf"/>
  <property name="senha"/>
  <property name="newsletter"/>
</hibernate-mapping>
Agora vou por também o bean Aluno que é uma subclasse de Usuario:
package br.infoteca.model.beans;

public class Aluno extends Usuario{

    //construtores
    public Aluno(int matricula, String nome, String email, int cpf, String senha, int newsletter) {
        super(matricula, nome, email, cpf, senha, newsletter);
    }

    public Aluno() {
    }
    
    //outros metodos
    public void resevar(){}
    
    public void inserirAlu(){}
    
    public void alterarInfoAlu(){}
    
    public void excluirAlu(){}
    
    public void procurarAlu(){}
    
}
A classe Usuario:
package br.infoteca.model.beans;

public class Usuario {

    //atributos
    private int matricula;
    private String nome;
    private String email;
    private int cpf;
    private String senha;
    private int newsletter;

    //construtres
    public Usuario() {
    }

    public Usuario(int matricula, String nome, String email, 
            int cpf, String senha, int newsletter) {
        this.matricula = matricula;
        this.nome = nome;
        this.email = email;
        this.cpf = cpf;
        this.senha = senha;
        this.newsletter = newsletter;
    }

    //Gets e Sets
    public int getCpf() {
        return cpf;
    }

    public void setCpf(int cpf) {
        this.cpf = cpf;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public int getMatricula() {
        return matricula;
    }

    public void setMatricula(int matricula) {
        this.matricula = matricula;
    }

    public int getNewsletter() {
        return newsletter;
    }

    public void setNewsletter(int newsletter) {
        this.newsletter = newsletter;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }
    
}

e aqui é a estrutura da tabela no banco de dados:
[img]http://www.adrive.com/home/downloadfile/758a54dc12b86677e04afae171f2f48890e4414bb38d662e07a6255774aa1b25[/img]

Eu sei que a postagem é muito grande e que a probabilidade de alguma alma caridosa me responder é pequena, mas gostaria muito de uma resposta, seja ela qual for. Desde já muitíssimo gratos a todos!

Abraços :)

5 Respostas

drsmachado

Já debugou para ver se os parâmetros chegam até o DAO?
Aliás, se você tem o bean, por que não o monta no servlet e passa apenas ele ao dao (ou melhor, cria um DTO para carregar esse Aluno até lá?)???

mirrah

bom cara, aqui vai uma perguntinha nub, como faço a depuração de um projeto meu no netbeans? rsrs

drsmachado

Velho, clicando em cima da barra lateral esquerda do código, onde fica a numeração das linhas, ele habilita breakpoints (quadrado vermelho). Então, você vai até o menu Depurar > Depurar projeto e ele irá rodar…
Coloque o breakpoint dentro do método. Com o cursor do mouse sobre a variável o nb abre uma tooltip com informações, no lado esquerdo deste tooltip, existirá um + para expandir.

mirrah

isso server para o netbeans 7.0 também? pois não estou com seguindo por os breakponts rsrs

drsmachado

Sim, eu uso o NB 7

Criado 4 de junho de 2011
Ultima resposta 4 de jun. de 2011
Respostas 5
Participantes 2