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;
}
}