Bom dia a todos.
Estou tentando aprender JAVA na marra a uns dois anos.
Não tenho muito tempo livre para isso, mas podem acreditar que todo o possíverl estou tentando desenvolver classes para agilizar meus desenvolvimentos, já que tenho que desenvolver o que me pedem.
Nesse momento estou tentando criar uma classe que persista …
Preciso criar esta classe (Abaixo), porém não desejo que a mesma seje instânciada. (Não sei bem se estou certo!). E esta dando o erro que disse no título desde tópico.
Se purem me ajudar, desde já agradeço.
Passo como parâmetro um objeto Tabela.
[code]/*
- 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;private ManutencaoTabela() {
//
}public static void IncluiRegistro(final Object Tabela, final Connection Conexao) {
this.ExecutaTransacao(this.PreparaInclusaoRegistro(Tabela));
}public static void AtualizaRegistro(final Object Tabela, final Connection Conexao) {
this.ExecutaTransacao(this.PreparaAlteracaoRegistro(Tabela));
}public static void ExcluiRegistro(final Object Tabela, final Connection Conexao) {
this.ExecutaTransacao(this.PreparaExclusaoRegistro(Tabela));
}public static void RecuperaRegistro(final Object Tabela, final Connection Conexao) {
this.ExecutaTransacao(this.PreparaRecuperacaoRegistro(Tabela));
}protected static void ExecutaTransacao(final String strSQL) {
String strNomeAtributo = new String();try { //Prepara transação PreparedStatement pstmt = this.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
// 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 = this.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 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 = this.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 String PreparaExclusaoRegistro(final Object Tabela) {
LinkedHashMap lhmAtributosClasse = new LinkedHashMap();
StringBuffer sbSQL = new StringBuffer();
String strNomeAtributo = new String();
//
lhmAtributosClasse = this.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 String PreparaRecuperacaoRegistro(final Object Tabela) {
LinkedHashMap lhmAtributosClasse = new LinkedHashMap();
StringBuffer sbSQL = new StringBuffer();
String strNomeAtributo = new String();
//
lhmAtributosClasse = this.getAtributosClasse(Tabela);
//Exclui Registro
sbSQL.append("SELECT 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(final Object Tabela) {
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()))) {
System.out.println("Valor do Método = " + methods[intValores].getName() + " - " + methods[intValores].invoke(tbTabela, new Object[0]));
if (methods[intValores].invoke(tbTabela, new Object[0]) != null) {
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;
}
}
[/code]