Ref.: Meu Hibernate

14 respostas
P

Boa tarde a todos.

Desenvolvi uma classe GENÉRICA para poder fazer manutenção de dados, passando assim, somente a classe de persistência e sua conecxão, porém gostaria de não precisar instâncea-la, tranformanda-a em uma CLASSE ABSTRATA.

Alguém pode me ajudar nessa empreitada?, já que estou tentando aprender JAVA na marra.

Desde já muito obrigado.

Seguem abaixo as classes para teste.

[color=red]A Classe Usuário (Persistência de Dados)[/color]

/*
 * Usuario.java
 *
 * Created on 16 de Junho de 2007, 21:58
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package tabelas;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import javax.swing.JOptionPane;

/**
 *
 * @author Paulo Roberto
 */
public class Usuario {
    private String NomeTabela;
    private Integer MatriculaChv;
    private String Nome;
    private String NomeGuerra;
    private GregorianCalendar DataCadastramento;
    private String Senha;
    private GregorianCalendar ValidadeSenha;
    
    /** Creates a new instance of Usuario */
    public Usuario() {
        this.NomeTabela = "tb_Usuarios";
    }
    
    public Usuario(final Integer MatriculaChv, final Connection Conexao) {
        this.NomeTabela = "tb_Usuarios";
    }
    
    public String getNomeTabela() {
        return this.NomeTabela;
    }
    
    public Integer getMatriculaChv() {
        return this.MatriculaChv;
    }
    
    public void setMatriculaChv(Integer MatriculaChv) {
        this.MatriculaChv = MatriculaChv;
    }
    
    public String getNome() {
        return this.Nome;
    }
    
    public void setNome(String Nome) {
        this.Nome = Nome;
    }
    
    public String getNomeGuerra() {
        return this.NomeGuerra;
    }
    
    public void setNomeGuerra(String NomeGuerra) {
        this.NomeGuerra = NomeGuerra;
    }
    
    public GregorianCalendar getDataCadastramento() {
        return this.DataCadastramento;
    }
    
    public void setDataCadastramento(GregorianCalendar DataCadastramento) {
        this.DataCadastramento = DataCadastramento;
    }
    
    public String getSenha() {
        return this.Senha;
    }
    
    public void setSenha(String Senha) {
        this.Senha = Senha;
    }
    
    public GregorianCalendar getValidadeSenha() {
        return this.ValidadeSenha;
    }
    
    public void setValidadeSenha(GregorianCalendar ValidadeSenha) {
        this.ValidadeSenha = ValidadeSenha;
    }
    
    public Usuario getUsuario(final Integer MatriculaChv, final Connection Conexao) {
        Usuario Usr = new Usuario(MatriculaChv, Conexao);
        
        return Usr;
    }
    
    public void setUsuario(Integer MatriculaChv, Connection Conexao)  {
        StringBuffer sbSQL = new StringBuffer()
        .append("SELECT Usuario.* ")
        .append("FROM Tb_Usuarios Usuario ")
        .append("WHERE Usuario.Matricula = " + MatriculaChv.toString());
        
        try {
            //Prepara transação
            PreparedStatement pstmt = Conexao.prepareStatement(sbSQL.toString());
            //Atribui valores aos Parâmetros
            //stmt.setString(1, "");
            //Cria resultado
            ResultSet rs = pstmt.executeQuery();
            
            if (rs.isBeforeFirst()) {
                while (rs.next()) {
                    System.out.println(rs.getString("Nome"));
                    
                    //Atribui valores as campos da classe
                    this.setMatriculaChv(rs.getInt("Matricula"));
                    this.setNome(rs.getString("Nome"));
                    this.setNomeGuerra(rs.getString("NomeGuerra"));
                    this.setDataCadastramento(new GregorianCalendar(2007, 3, 14));
                    this.setSenha(rs.getString("Senha"));
                    this.setValidadeSenha(new GregorianCalendar(2007, 3, 14));
                }
            }
            //Consolida transação
            Conexao.commit();
            //Fecha conexão
            pstmt.close();
            //Mostra String SQL
            System.out.println(sbSQL);
        } catch (SQLException errorSQL) {
            JOptionPane.showMessageDialog(null, errorSQL.getMessage(), "Erro SQL", JOptionPane.ERROR_MESSAGE);
            errorSQL.printStackTrace();
        }
    }

}

[color=red]A chamada[/color]

//Teste de Persistência de Dados
        //=====================================
        Usuario u = new Usuario();
        u.setMatriculaChv(3);
        u.setNome("Beltrano de Tal");
        u.setNomeGuerra("Beltrano");
        u.setDataCadastramento(new GregorianCalendar(2007, 5, 14));
        u.setSenha("333333");
        u.setValidadeSenha(new GregorianCalendar(2007, 6, 10));
        

        //========= EXATAMENTE AQUI NÃO DESEJO INSTÂNCIAR ManutencaoTabela ======  Como faço então?
        ManutencaoTabela mt = new ManutencaoTabela(u, cnn);

        //Ora isso.
        mt.IncluiRegistro();

         //Ora isso.
       mt.AtualizaRegistro();

         //Ora isso.
       mt.ExcluiRegistro();
       //=====================================

[color=red]Agora a classe propriamente dita. (A que desejo transformar em CLASSE ABSTRATA)[/color]

/*
 * ManutencaoTabela.java
 *
 * Created on 23 de Junho de 2007, 21:01
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package manutencoes;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.LinkedHashMap;
import javax.swing.JOptionPane;

/**
 *
 * @author Paulo Roberto
 */
public class ManutencaoTabela {
    private Object tbTabela;
    private Class clsTabela;
    private String strNomeTabela;
    private LinkedHashMap lhmAtributosClasse;
    private Connection Conexao;
    
    public ManutencaoTabela(final Object Tabela, final Connection Conexao) {
        this.tbTabela = Tabela;
        this.clsTabela = Tabela.getClass();
        this.lhmAtributosClasse = this.getAtributosClasse();
        this.Conexao = Conexao;
    }
    
    public void IncluiRegistro() {
        this.ExecutaTransacao(this.PreparaInclusaoRegistro());
    }
    
    public void AtualizaRegistro() {
        this.ExecutaTransacao(this.PreparaAlteracaoRegistro());
    }
    
    public void ExcluiRegistro() {
        this.ExecutaTransacao(this.PreparaExclusaoRegistro());
    }
    
    private void ExecutaTransacao(final String strSQL) {
        String strNomeAtributo = new String();
        
        try {
            //Prepara transação
            PreparedStatement pstmt = Conexao.prepareStatement(strSQL);
            
            //Atribui valores aos parâmetros
            int i = 0;
            
            //Inclusão
            if (strSQL.indexOf("INSERT INTO") > -1) {
                //Parêmetros da contexto da QUERY
                for (Iterator it = lhmAtributosClasse.keySet().iterator(); it.hasNext(); ) {
                    strNomeAtributo = it.next().toString();
                    
                    if (!strNomeAtributo.equals("NomeTabela") && !strNomeAtributo.substring(strNomeAtributo.length()-3, strNomeAtributo.length()).equals("Chv")) {
                        i++;
                        pstmt = TrataParametro(pstmt, i, lhmAtributosClasse.get(strNomeAtributo));
//                        System.out.println("Nome da Coluna: " + pstmt.getMetaData().getColumnName(i));
                    }
                }
            } else if (strSQL.indexOf("UPDATE") > -1) {
                //Parêmetros da contexto da QUERY
                for (Iterator it = lhmAtributosClasse.keySet().iterator(); it.hasNext(); ) {
                    strNomeAtributo = it.next().toString();
                    
                    if (!strNomeAtributo.equals("NomeTabela") && !strNomeAtributo.substring(strNomeAtributo.length()-3, strNomeAtributo.length()).equals("Chv")) {
                        i++;
                        pstmt = TrataParametro(pstmt, i, lhmAtributosClasse.get(strNomeAtributo));
//                        System.out.println("Nome da Coluna: " + pstmt.getMetaData().getColumnName(i));
                    }
                }
                
                //Parêmetros da cláusula WHERE
                for (Iterator it = lhmAtributosClasse.keySet().iterator(); it.hasNext(); ) {
                    strNomeAtributo = it.next().toString();
                    
                    if (strNomeAtributo.substring(strNomeAtributo.length()-3, strNomeAtributo.length()).equals("Chv")) {
                        i++;
                        pstmt = TrataParametro(pstmt, i, lhmAtributosClasse.get(strNomeAtributo));
//                        System.out.println("Nome da Coluna: " + pstmt.getMetaData().getColumnName(i));
                    }
                }
            } else if (strSQL.indexOf("DELETE FROM") > -1) {
                //Parêmetros da cláusula WHERE
                for (Iterator it = lhmAtributosClasse.keySet().iterator(); it.hasNext(); ) {
                    strNomeAtributo = it.next().toString();
                    
                    if (strNomeAtributo.substring(strNomeAtributo.length()-3, strNomeAtributo.length()).equals("Chv")) {
                        i++;
                        pstmt = TrataParametro(pstmt, i, lhmAtributosClasse.get(strNomeAtributo));
//                        System.out.println("Nome da Coluna: " + pstmt.getMetaData().getColumnName(i));
                    }
                }
            }
            
            //Mostra parâmetros e seus respectivos valores - (Esta PORRA!, não Funciona com alguns Drivers. Inclusive este!)
            System.out.println("Parâmetros ...");

//////////            ParameterMetaData pmd = pstmt.getParameterMetaData();
//////////
//////////            for (int i2 = 1; i2 < pmd.getParameterCount(); i2++) {
//////////                System.out.println("Parameter number " + i2);
//////////                System.out.println("  Class name is " + pmd.getParameterClassName(i2));
//////////                // Note: Mode relates to input, output or inout
//////////                System.out.println("  Mode is " + pmd.getParameterClassName(i2));
//////////                System.out.println("  Type is " + pmd.getParameterType(i2));
//////////                System.out.println("  Type name is " + pmd.getParameterTypeName(i2));
//////////                System.out.println("  Precision is " + pmd.getPrecision(i2));
//////////                System.out.println("  Scale is " + pmd.getScale(i2));
//////////                System.out.println("  Nullable? is " + pmd.isNullable(i2));
//////////                System.out.println("  Signed? is " + pmd.isSigned(i2));
//////////            }
            
            //Mostra String SQL
            System.out.println(strSQL);
            
            //Executa  procedimento
            pstmt.executeUpdate();
            
            //Fecha procedimento
            pstmt.close();
            
            //Fecha conexão
            Conexao.close();
        } catch (SQLException errorSQL) {
            JOptionPane.showMessageDialog(null, errorSQL.getMessage(), "Erro SQL", JOptionPane.ERROR_MESSAGE);
            errorSQL.printStackTrace();
        }
    }
    
    private String PreparaInclusaoRegistro() {
        StringBuffer sbSQL = new StringBuffer();
        String strNomeAtributo = new String();
        
        //Inclui Registro
        sbSQL.append("INSERT INTO ").append(lhmAtributosClasse.get("NomeTabela") + " ");
        sbSQL.append("(");
        
        //Lista as entradas (Campos da Tabela)
        for (Iterator it = lhmAtributosClasse.keySet().iterator(); it.hasNext(); ) {
            strNomeAtributo = it.next().toString();
            
            if (!strNomeAtributo.equals("NomeTabela") && !strNomeAtributo.substring(strNomeAtributo.length()-3, strNomeAtributo.length()).equals("Chv")) {
                sbSQL.append(strNomeAtributo).append((", "));
            }
        }
        
        //Retira o excesso
        sbSQL.delete(sbSQL.length() - 2, sbSQL.length());
        
        sbSQL.append(") VALUES (");
        
        //Lista as entradas (Parâmetros)
        for (Iterator it = lhmAtributosClasse.keySet().iterator(); it.hasNext(); ) {
            strNomeAtributo = it.next().toString();
            
            if (!strNomeAtributo.equals("NomeTabela") && !strNomeAtributo.substring(strNomeAtributo.length()-3, strNomeAtributo.length()).equals("Chv")) {
                sbSQL.append("?, ");
            }
        }
        
        //Retira o excesso
        sbSQL.delete(sbSQL.length() - 2, sbSQL.length());
        
        sbSQL.append(")");
        
        return sbSQL.toString();
    }
    
    private String PreparaAlteracaoRegistro() {
        StringBuffer sbSQL = new StringBuffer();
        String strNomeAtributo = new String();
        
        //Alterar Registro
        sbSQL.append("UPDATE ").append(lhmAtributosClasse.get("NomeTabela") + " SET ");
        
        //Remove o campo que contém o nome da tabela
        lhmAtributosClasse.remove("NomeTabela");
        
        //Lista as entradas (Campos da Tabela/Parâmetros)
        for (Iterator it = lhmAtributosClasse.keySet().iterator(); it.hasNext(); ) {
            strNomeAtributo = it.next().toString();
            
            if (!strNomeAtributo.equals("NomeTabela") && !strNomeAtributo.substring(strNomeAtributo.length()-3, strNomeAtributo.length()).equals("Chv")) {
                sbSQL.append(strNomeAtributo).append(" = ").append("?, ");
            }
        }
        
        //Retira o excesso
        sbSQL.delete(sbSQL.length() - 2, sbSQL.length()).append(" ");
        
        sbSQL.append("WHERE ");
        
        //Lista as entradas (Campos Chave)
        for (Iterator it = lhmAtributosClasse.keySet().iterator(); it.hasNext(); ) {
            strNomeAtributo = it.next().toString();
            
            if (strNomeAtributo.substring(strNomeAtributo.length()-3, strNomeAtributo.length()).equals("Chv")) {
                sbSQL.append(strNomeAtributo).append(" = ").append("?, ");
            }
        }
        
        //Retira o excesso
        sbSQL.delete(sbSQL.length() - 2, sbSQL.length());
        
        return sbSQL.toString();
    }
    
    private String PreparaExclusaoRegistro() {
        StringBuffer sbSQL = new StringBuffer();
        String strNomeAtributo = new String();
        
        //Exclui Registro
        sbSQL.append("DELETE FROM ").append(lhmAtributosClasse.get("NomeTabela") + " ");
        
        sbSQL.append("WHERE ");
        
        //Lista as entradas (Campos Chave)
        for (Iterator it = lhmAtributosClasse.keySet().iterator(); it.hasNext(); ) {
            strNomeAtributo = it.next().toString();
            
            if (strNomeAtributo.substring(strNomeAtributo.length()-3, strNomeAtributo.length()).equals("Chv")) {
                sbSQL.append(strNomeAtributo).append(" = ").append("?, ");
            }
        }
        
        //Retira o excesso
        sbSQL.delete(sbSQL.length() - 2, sbSQL.length()).append(" ");
        
        return sbSQL.toString();
    }
    
    protected LinkedHashMap getAtributosClasse() {
        LinkedHashMap lhmAtributosClasse = new LinkedHashMap();
        
        //Campos (Nomes dos atributos)
        Field fields[] = clsTabela.getDeclaredFields();
        for (int intCampos = 0; intCampos < fields.length; intCampos++) {
            lhmAtributosClasse.put(fields[intCampos].getName(), null);
        }
        
        //Métodos (Valores dos atributos)
        Method methods[] = clsTabela.getDeclaredMethods();
        for (int intValores = 0; intValores < methods.length; intValores++) {
            if(!methods[intValores].getReturnType().equals(Void.class) && methods[intValores].getParameterTypes().length <= 0) {
                try {
                    if (lhmAtributosClasse.containsKey(methods[intValores].getName().substring(3, methods[intValores].getName().length()))) {
                        lhmAtributosClasse.put(methods[intValores].getName().substring(3, methods[intValores].getName().length()), methods[intValores].invoke(tbTabela, new Object[0]));
                    }
                } catch (IllegalArgumentException ex) {
                    ex.printStackTrace();
                } catch (InvocationTargetException ex) {
                    ex.printStackTrace();
                } catch (IllegalAccessException ex) {
                    ex.printStackTrace();
                }
            }
        }
        
        return lhmAtributosClasse;
    }
    
    protected PreparedStatement TrataParametro(final PreparedStatement pstmt, final int i, final Object Objeto) throws SQLException {
        PreparedStatement pstmt2 = pstmt;
        
        //Trata o parâmetro
        if(Objeto instanceof GregorianCalendar) {
            pstmt2.setDate(i, new java.sql.Date(((GregorianCalendar) Objeto).getTime().getTime()));
        } else if (Objeto instanceof String) {
            pstmt2.setString(i, (String) Objeto);
        } else if (Objeto instanceof Integer) {
            pstmt2.setInt(i, (Integer) Objeto);
        } else {
            pstmt2.setString(i, "Null");
        }
        
        return pstmt2;
    }

}

14 Respostas

Thiagoprudente

vc já ouviu falar em Listener?

package servlet;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;

public class Listener implements ServletContextListener {

public void contextDestroyed(ServletContextEvent arg0) {
	// TODO Auto-generated method stub
	
}

public void contextInitialized(ServletContextEvent arg0) {
	Logger loggerConnect = Logger.getLogger("Connect");
	try  {
		loggerConnect.debug("In HibernateAppListener.contextInitialized");

		[b]Class.forName("bean.HibernateUtil").newInstance();[/b]
		loggerConnect.debug("In HibernateAppListener, Class.forName for tomcatJndi.HibernateUtil successful");
	}
	catch (Exception e)  {
		loggerConnect.debug("In HibernateAppListener, Class.forName for tomcatJndi.HibernateUtil throws Exception");
	}
}

}

meu hibernateUtil:

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
private static final SessionFactory sessionFactory;

static { 
	try { 
		 
		sessionFactory = new Configuration().configure().buildSessionFactory(); 
	} catch (Throwable e) { 
		e.printStackTrace(); 
		throw new ExceptionInInitializerError(e); 
	} 

}

public static SessionFactory getSessionFactory() {
	
	return sessionFactory;
}

}

acho que o segredo está em declarar como final uma variável que vc deseja na sua classe e criar uma outra classe listener, depois que vc criar a classe listener deve colocar no web.xml que está no web-inf a seguinte configuração:
servlet.Listener // aqui é onde está sua classe listener como o pacote onde ela está

espero ter ajudado

P

Blz!

Acabei de chegar do trampo.

Irei examinar amnhã cedo.

Outra coisa:
o que achou de minha idéia?

Sei que reinventei a roda, porém usarei isso em minhas aplicações, desta forma criarei minha própria biblioteca, mais enxuta e mais rápida.

Concorda?

Valeu abraços.

Thiagoprudente

Concordo!

Deixa eu te perguntar uma coisa, vc já teve que criar um novo dialeto pra um banco que não está registrado no dialect? eu tô precisando fazer isso pro meu banco pois ele é Adabas e não está registrado lá no dialect…
vc já teve que fazer isso? Se não fez sabe como fazer?

P

Pô cara!

Não tenho noção do que está me pedindo.

Me perdoe, pois como disse antes, estou tentando aprender JAVA na marra.

Não tenho muito com quem trocar idéias.

Thiagoprudente

beleza!! vc pode trocar idéia comigo à vontade ok!!
o que vc já sabe de java? de repente eu posso te ajudar!

P

Obrigado!

A princípio pretendo descobrir como transformar linha classe ManutencaoTabela em uma Classe Abstrata.

Só isso.

Porém não quero usar nada de HIBERNATE.

Quero simplesmente o Básico.

Se puder me adiantar, desde já lhe sou muito grato.

Vc. pode até fazer modificações na CLASSE!

Thiagoprudente

Eu também não sou tão bom assim em java, eu andei pesquisando aqui e vi que classe abstrata é uma classe que na realidade não serve pra nada, apenas para ser utilizada como subsideo para as suas subclasses!
Veja o exemplo abaixo:

public abstract class pessoa{

public int idade=8;

}

uma subclasse da classe aluno

public class aluno extends pessoa{

idade = 3;

}

ela serve simplesmente para reaproveitamento de código!!!

Thiagoprudente

corrigindo o código acima…

public abstract class pessoa{

public int idade=8;

}

uma subclasse da classe pessoa

public class aluno extends pessoa{

idade = 3;

}
P

No meu caso, pretendo fazer uma classe que tenha vários métodos e que depois possa usá-los sempre que for possível sem precisar instaciar a classe.

É disso que exatamente preciso.

Thiagoprudente

vc está usando web applicação?
procure sobre classe listener então!!

P

Não!

DeskTop Application!

ddduran

prsantos:
No meu caso, pretendo fazer uma classe que tenha vários métodos e que depois possa usá-los sempre que for possível sem precisar instaciar a classe.

É disso que exatamente preciso.

Olha não entendi direito pra que você quer isso, pra falar a verdade nem por que você quer isso, mas ai vai

se você quer usar um metodo sem ter que instanciar uma classe o que você quer é um metodo estatico com o modificador STATIC não uma classe abstrata que não tem nada haver com não instanciar.

eu aconselho você a estudar melhor alguns conceitos de OO e de Java basico.
da uma olhada nesse tutorial
http://www.guj.com.br/java.tutorial.artigo.121.1.guj
e
http://www.guj.com.br/java.tutorial.artigo.149.1.guj

bom espero que ajude.

PS: o que listener tem haver com tudo isso?

Thiagoprudente

desculpa a demora…

o meu problema é só criar um dialeto pro meu banco que não tem no hibernate!! depois que vc ficar mais avançado em java, vai conhecer algo chamado hibernate!!

mas sobre o listener, é o seguinte ele instancia uma classe pra vc na hora em que roda o projeto, aí é só vc usar a sua classe listener em outra classe como se fosse uma função do java!!

P

Valeu Duran Duran!

Ajudou sim!

Criado 24 de outubro de 2007
Ultima resposta 25 de out. de 2007
Respostas 14
Participantes 3