Podem avaliar se o que fiz está certo?
Funcionando está com certeza!
Só preciso saber se estou desenvolvendo direito.
[color=red]Exemplo[/color]
Usuario u1 = new Usuario();
u1.setMatriculaChv(1);
u1.setNomeGuerra("Beltrano");
ManutencaoTabela.AtualizaRegistro(u1, cnn);
Usuario u2 = new Usuario();
u2.setMatriculaChv(2);
u2.setNomeGuerra("Ciclano");
ManutencaoTabela.AtualizaRegistro(u2, cnn);
Usuario u3 = new Usuario();
u3.setMatriculaChv(4);
u3.setNomeGuerra("Fulano");
ManutencaoTabela.IncluiRegistro(u3, cnn);
[color=red]Minha classe Usuário[/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 bancodados.BancoDados;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.JOptionPane;
import manutencoes.ManutencaoTabela;
/**
*
* @author Paulo Roberto
*/
public class Usuario {
private String strNomeTabela;
private Connection cnnConexao;
private Integer intMatriculaChv;
private String strNome;
private String strNomeGuerra;
private GregorianCalendar gcDataCadastramento;
private String strSenha;
private GregorianCalendar gcValidadeSenha;
/** Creates a new instance of Usuario */
public Usuario() {
this.strNomeTabela = "tb_Usuarios";
}
public Usuario(final Integer intMatriculaChv, final Connection cnnConexao) {
this.strNomeTabela = "tb_Usuarios";
this.cnnConexao = cnnConexao;
this.intMatriculaChv = intMatriculaChv;
StringBuffer sbSQL = new StringBuffer()
.append("SELECT Usuario.* ")
.append("FROM Tb_Usuarios Usuario ")
.append("WHERE Usuario.MatriculaChv = " + this.intMatriculaChv.toString());
ResultSet rs = BancoDados.FabricaCosulta(sbSQL, cnnConexao);
try {
// if (rs.isBeforeFirst()) {
while (rs.next()) {
//Atribui valores aos atributos da classe
this.setMatriculaChv(rs.getInt("MatriculaChv"));
this.setNome(rs.getString("Nome"));
this.setNomeGuerra(rs.getString("NomeGuerra"));
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(rs.getDate("DataCadastramento"));
this.setDataCadastramento(gc);
this.setSenha(rs.getString("Senha"));
gc.setTime(rs.getDate("ValidadeSenha"));
this.setValidadeSenha(gc);
}
// }
} catch (SQLException errorSQL) {
JOptionPane.showMessageDialog(null, errorSQL.getMessage(), "Erro SQL", JOptionPane.ERROR_MESSAGE);
errorSQL.printStackTrace();
}
}
public String getNomeTabela() {
return this.strNomeTabela;
}
public Integer getMatriculaChv() {
return this.intMatriculaChv;
}
public void setMatriculaChv(Integer intMatriculaChv) {
this.intMatriculaChv = intMatriculaChv;
}
public String getNome() {
return this.strNome;
}
public void setNome(String strNome) {
this.strNome = strNome;
}
public String getNomeGuerra() {
return this.strNomeGuerra;
}
public void setNomeGuerra(String strNomeGuerra) {
this.strNomeGuerra = strNomeGuerra;
}
public GregorianCalendar getDataCadastramento() {
return this.gcDataCadastramento;
}
public void setDataCadastramento(GregorianCalendar gcDataCadastramento) {
this.gcDataCadastramento = gcDataCadastramento;
}
public String getSenha() {
return this.strSenha;
}
public void setSenha(String strSenha) {
this.strSenha = strSenha;
}
public GregorianCalendar getValidadeSenha() {
return this.gcValidadeSenha;
}
public void setValidadeSenha(GregorianCalendar gcValidadeSenha) {
this.gcValidadeSenha = gcValidadeSenha;
}
}
[color=red]Agora Minha Classe que faz a manutenção do banco[/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 ManutencaoTabela() {
//
}
public static void IncluiRegistro(final Object Tabela, final Connection Conexao) {
ExecutaTransacao(PreparaInclusaoRegistro(Tabela), getAtributosClasse(Tabela), Conexao);
}
public static void AtualizaRegistro(final Object Tabela, final Connection Conexao) {
ExecutaTransacao(PreparaAlteracaoRegistro(Tabela), getAtributosClasse(Tabela), Conexao);
}
public static void ExcluiRegistro(final Object Tabela, final Connection Conexao) {
ExecutaTransacao(PreparaExclusaoRegistro(Tabela), getAtributosClasse(Tabela), Conexao);
}
public static void RecuperaRegistro(final Object Tabela, final Connection Conexao) {
ExecutaTransacao(PreparaRecuperacaoRegistro(Tabela), getAtributosClasse(Tabela), Conexao);
}
protected static void ExecutaTransacao(final String strSQL, final LinkedHashMap lhmAtributosClasse, final Connection Conexao) {
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));
}
}
//Executa procedimento
pstmt.executeUpdate();
} 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));
}
}
//Executa procedimento
pstmt.executeUpdate();
} 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));
}
}
//Executa procedimento
pstmt.executeUpdate();
} else if (strSQL.indexOf("SELECT 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));
}
}
//Executa procedimento
pstmt.executeQuery();
}
////////// //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);
//Fecha procedimento
pstmt.close();
// //Fecha conexão
// this.Conexao.close();
} catch (SQLException errorSQL) {
JOptionPane.showMessageDialog(null, errorSQL.getMessage(), "Erro SQL", JOptionPane.ERROR_MESSAGE);
errorSQL.printStackTrace();
}
}
protected static String PreparaInclusaoRegistro(final Object Tabela) {
LinkedHashMap lhmAtributosClasse = new LinkedHashMap();
StringBuffer sbSQL = new StringBuffer();
String strNomeAtributo = new String();
//
lhmAtributosClasse = getAtributosClasse(Tabela);
//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();
}
protected static String PreparaAlteracaoRegistro(final Object Tabela) {
// if (lhmAtributosClasse.containsKey("MatriculaChv"))
// throw new IllegalArgumentException("O mapa deve conter o ItemEspecial!");
LinkedHashMap lhmAtributosClasse = new LinkedHashMap();
StringBuffer sbSQL = new StringBuffer();
String strNomeAtributo = new String();
//
lhmAtributosClasse = getAtributosClasse(Tabela);
//Alterar Registro
sbSQL.append("UPDATE ").append(lhmAtributosClasse.get("NomeTabela") + " SET ");
//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();
}
protected static String PreparaExclusaoRegistro(final Object Tabela) {
LinkedHashMap lhmAtributosClasse = new LinkedHashMap();
StringBuffer sbSQL = new StringBuffer();
String strNomeAtributo = new String();
//
lhmAtributosClasse = getAtributosClasse(Tabela);
//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 static String PreparaRecuperacaoRegistro(final Object Tabela) {
LinkedHashMap lhmAtributosClasse = new LinkedHashMap();
StringBuffer sbSQL = new StringBuffer();
String strNomeAtributo = new String();
//
lhmAtributosClasse = getAtributosClasse(Tabela);
//Exclui Registro
sbSQL.append("SELECT FROM ");
//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(", ");
}
}
//Retira o excesso
sbSQL.delete(sbSQL.length() - 2, sbSQL.length()).append(" ");
sbSQL.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 static LinkedHashMap getAtributosClasse(final Object Tabela) {
LinkedHashMap lhmAtributosClasse = new LinkedHashMap();
// //Campos (Nomes dos atributos)
// Field fields[] = Tabela.getClass().getDeclaredMethods();
// for (int intCampos = 0; intCampos < fields.length; intCampos++) {
// lhmAtributosClasse.put(fields[intCampos].getName(), null);
// }
//Métodos (Valores dos atributos)
Method methods[] = Tabela.getClass().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()))) {
System.out.println("Valor do Método = " + methods[intValores].getName() + " - " + methods[intValores].invoke(Tabela, new Object[0]));
if (methods[intValores].invoke(Tabela, new Object[0]) != null) {
lhmAtributosClasse.put(methods[intValores].getName().substring(3, methods[intValores].getName().length()), methods[intValores].invoke(Tabela, new Object[0]));
}
//}
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (InvocationTargetException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
}
return lhmAtributosClasse;
}
protected static 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;
}
}