Dao

Olá guj…

estou postando um trecho de uma de minhas classes DAO ( infelizmente nao consegui atualizar pra hibernate ainda )… enfim, gostaria que quem tiver saco pra olhar, me desse alguma dica de como eu poderia melhorá-la…

public void cadastrar(CaracteristicaIndividuo caracteristica, 
		RegistroCriminal registroCriminal, Connection conn)
		throws Exception {	
		
		PreparedStatement stmt = null;

		StringBuffer sql = null;

		try {
			
			if ( caracteristica.getId() < 0 ) {
				sql = new StringBuffer();
				sql.append(" SELECT MAX(CD_CARACTERISTICA_INDIVIDUO) AS CONTADOR FROM RCR_CARACTERISTICAS_INDIVIDUO ");
				sql.append(" WHERE CD_REGISTRO_CRIMINAL = ? ");
				stmt = conn.prepareStatement(
					sql.toString());
				stmt.setLong(1, registroCriminal.getId());
				ResultSet rs = stmt.executeQuery();
				rs.next();
				caracteristica.setId( rs.getInt("CONTADOR") + 1 );
			}
			
			sql = new StringBuffer();
			
			sql.append(" INSERT INTO RCR_CARACTERISTICAS_INDIVIDUO");
			sql.append(" ( CD_REGISTRO_CRIMINAL");
			sql.append(" , CD_GRUPO_CARACTERISTICA");
			sql.append(" , CD_TIPO_CARACTERISTICA");
			sql.append(" , CD_CARACTERISTICA");
			sql.append(" , CD_CARACTERISTICA_INDIVIDUO");
			sql.append(" , DS_CARACTERISTICAS");
			sql.append(" , DT_CADASTRO");
			sql.append(" , ST_INFORMACAO)");
			sql.append(" VALUES(?,?,?,?,?,?,?,?)");

			stmt = conn.prepareStatement(sql.toString());
			
			stmt.setLong(1, registroCriminal.getId());
			stmt.setLong(2, caracteristica.getGrupoCaracteristica().getId());
			stmt.setLong(3, caracteristica.getTipoCaracteristica().getId());
			stmt.setLong(4, caracteristica.getCaracteristica().getId());
			stmt.setLong(5, caracteristica.getId());
			stmt.setString(6, caracteristica.getDescricao());
			stmt.setTimestamp(7, caracteristica.getData());
			stmt.setString(8, "A");
			
			stmt.execute();
			
		} catch (Exception e) {
			if( e.getMessage() != null && e.getMessage().contains("violation of PRIMARY or UNIQUE KEY")){
				throw new Exception("Não é possível inserir a mesma característica.");
			} else {
				throw new Exception("Erro ao inserir característica. " + e.getMessage());
			}
		} finally {
			try {
				if ( stmt != null )
					stmt.close();
			} catch ( Exception e ) {
				throw e;
			}
		}
		
	}

Abraços

Cara, se não for utilizar hibernate… vou te postar a classe que fiz para fazer este controle… ela funciona apartir de ARRAYS, ou seja … é um MINI “frameworkzinho”, que usado da maneira correta, funciona muito bem…

PS: os array deve estar com o conteúdo na ordem do seu banco, ou seja… se a terceira coluna do seu banco, for para estar nula… array[2] = null considerando array[0] a primeira coluna!

lá vai:

/*

  • Dao.java
  • Created on 16 de Março de 2007, 09:12
  • To change this template, choose Tools | Template Manager
  • and open the template in the editor.
    */

[code]package bibliotecas;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

/**
*

  • @author root
    */

public class Dao {
final String banco = “CPADI”;
public gDao gd = new gDao();

/** Creates a new instance of Dao */
public Dao() {
}
   
//faz a conexão com o banco
  public java.sql.Connection  conn() throws ClassNotFoundException, SQLException  {
    Connection c; 
    Class.forName("com.mysql.jdbc.Driver");
    String query = "jdbc:mysql://localhost/" + banco + "?user=root";
    c = DriverManager.getConnection(query);
    return c;
}


//Retorna o tamanho de um array preenchido
public int lengthArray(String [] array) {
    boolean b = true; int i = 0;
    while (b) {
      if (array[i] != null)
        i++;
      else
        b = false;
    }
    return i;
}

//retorna os preparos do statement "?,..,?""
public String createFields(String[] interrogacao) {
    boolean b = true; int i = 0;
    String retorno = "";
    while (b) {
        if (interrogacao[i] != null)
            if (interrogacao[i+1] == null) retorno+="?";
            else retorno += "?,";
        else
          b = false;
        i++;
    }
    return retorno;
}

/*
 * Adiciona à tabela passando como argumentos o nome da tabela e uma array com os dados
 * @params AddTable(tabela, array_valores);
 */
public void addTable(String table, String[] values) throws SQLException, ClassNotFoundException {
    PreparedStatement pst;
    String execute;
    execute = "insert into "+table+" values ("+createFields(values)+")";
    pst = conn().prepareStatement(execute);    
    for (int i = 0;i<lengthArray(values);i++)
      pst.setString(i+1,values[i]); 

    pst.execute();
    pst.close();
    conn().close();
}

/*
 * Atualiza à tabela como argumentos o nome da tabela, campoID, indexValor e um array com os dados
 * @params uptTable(tabela, c1, c2, array_valores); 
 */
//update table where c1 = c2 set v = 1, v2 = 2, v3 = 3;
public void uptTable(String table, String c1, String c2, String [] values) throws ClassNotFoundException, SQLException {
  //Faz uma conexão rápida com o banco, para pegar os metadados
  Statement stmt = conn().createStatement();
  stmt = conn().createStatement(); 
  ResultSet rset = stmt.executeQuery("SELECT * from "+table);
  ResultSetMetaData rsmd = rset.getMetaData();
  int numColumns = rsmd.getColumnCount();
  String aux = "";
   for (int i=0; i<numColumns; i++) 
     aux += rsmd.getColumnName (i + 1)+" = ?, ";   
  PreparedStatement pst;
  String execute;
  execute = "Update "+table+" set "+aux;
  String copi = "";
  String execute_2 = copi.copyValueOf(execute.toCharArray(),0,execute.length()-2).toString();
  execute_2 += " where "+c1+" = "+c2;      
  pst = conn().prepareStatement(execute_2);
  for (int i = 0;i<lengthArray(values);i++)
      pst.setString(i+1,values[i]); 
    pst.execute();
    pst.close();
    conn().close();
}

}
[/code]

qualquer dúvida, pode perguntar por aqui msmo… abraços