(RESOLVIDO)Retornar apenas 1 registro específico na tabela(CLASSE DAO)

2 respostas Resolvido
programaçãoerroserrorexceptionjava
G

Sou iniciante no mundo Java, e estou estudando o Design Pattern DAO e iniciando Java WEB, porém me desafiei a listar apenas um registro da tabela, retornando um objeto do tipo funcionário. Entretanto na hora de executar o java me retorna um NullPointerException.

Segue o código abaixo:

public Funcionario pesquisar(int id) {
    
    try {
        PreparedStatement pstm = this.connection.prepareStatement("SELECT * FROM funcionario "
                + "WHERE id = ?");
        pstm.setLong(1, id);
        ResultSet rs = pstm.executeQuery();
        Funcionario funcionario = new Funcionario();
        while(rs.next()) {
            funcionario.setNome(rs.getString("nome"));
            funcionario.setUsuario(rs.getString("usuario"));
            funcionario.setSenha(rs.getString("senha"));
            Calendar dataAtual = Calendar.getInstance();
            dataAtual.setTime(new Date(funcionario.getDataAtual().getTimeInMillis()));
            funcionario.setDataAtual(dataAtual);
        }
        return funcionario;
    }catch(SQLException e) {
        throw new RuntimeException(e);
    }
}`

Classe teste

package br.com.gustavo.teste.funcionario;

import br.com.gustavo.dao.FuncionarioDAO;
import br.com.gustavo.modelo.Funcionario;

public class TestaPesquisar {

public static void main(String[] args) {
    
    Funcionario funcionario = new FuncionarioDAO().pesquisar(5);
    System.out.println("Nome: "+funcionario.getNome());
    }
    
 }

2 Respostas

J

Coloque o método pesquisar como static

No método main você faz assim:

System.out.print(FuncionarioDAO.pesquisar(5));

Acontece do NullPointerExcepion, porque você está criando dois objetos, um no metodo pesquisar e outro no metodo main

E não se esqueça de colocar o toString() na classe Funcionario

D
Solucao aceita

Uma coisa quando se traz um único registro não precisa fazer while um simples if (res.next()) { é o suficiente.

Código Exemplo:

@Override
public Funcionario find(Long id) {
	PreparedStatement st;
	Funcionario func = null;
	try {            
		st = connection
				.prepareStatement("SELECT id, nome FROM funcionario WHERE id=? limit 1", true);
		
		st.setLong(1, id);            
		try (ResultSet res = st.executeQuery()) {
			if (res.next())
			{
				func = new Funcionario(res.getLong(1), res.getString(2));
			}
		}
		st.close();            
		return func;
	} catch (SQLException | ClassNotFoundException ex) {
		Logger.getLogger(DalFuncionario.class.getName()).log(Level.SEVERE, null, ex);
	}
	return func;
}

Para utilizar:

Connection connection = new Connection();
DalFuncionario dalFunc = new DalFuncionario(connection);
Funcionario func = dalFunc.find(2L);
System.out.println(func.getId() + " " + func.getNome());

Dessa forma funciona perfeitamente: Aviso, não crie métodos como static, crie um Interface genérica para que seus métodos DAL fiquem todos padrão.

Exemplo:

public interface IDal<T, T1> {
    public T insert(T model);
    public boolean edit(T model);
    public T find(T1 id);
}

Implementação:

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DalFuncionario implements IDal<Funcionario, Long>{
    private final Connection connection;

    public DalFuncionario(Connection connection) {
        this.connection = connection;
    }

    @Override
    public Funcionario insert(Funcionario model) {
        
        try {
            PreparedStatement st = connection
                    .prepareStatement("INSERT INTO funcionario(nome) values(?)", true);            
            st.setString(1, model.getNome());            
            if (st.executeUpdate() > 0) {
                try (ResultSet res = st.getGeneratedKeys()) {
                    if (res.next()){
                        model.setId(res.getInt(1));
                        res.close();
                        st.close();
                        return model;
                    }
                }
                st.close();
            }            
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(DalFuncionario.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    @Override
    public boolean edit(Funcionario model) {
        try {
            PreparedStatement st = connection 
                    .prepareStatement("UPDATE funcionario SET nome=? WHERE id =?", true);
            st.setString(1, model.getNome()); 
            st.setLong(2, model.getId()); 
            return (st.executeUpdate() > 0);
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(DalFuncionario.class.getName()).log(Level.SEVERE, null, ex);
        }
        return Boolean.FALSE;
    }
    
    @Override
    public Funcionario find(Long id) {
        PreparedStatement st;
        Funcionario func = null;
        try {            
            st = connection
                    .prepareStatement("SELECT id, nome FROM funcionario WHERE id=? limit 1", true);
            
            st.setLong(1, id);            
            try (ResultSet res = st.executeQuery()) {
                if (res.next())
                {
                    func = new Funcionario(res.getLong(1), res.getString(2));
                }
            }
            st.close();            
            return func;
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(DalFuncionario.class.getName()).log(Level.SEVERE, null, ex);
        }
        return func;
    }  
}

Classe Connection

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class Connection {
    private java.sql.Connection connect = null;

    public Connection() throws ClassNotFoundException, SQLException 
    {
        open();
    }
    
    public java.sql.Connection open() throws SQLException, ClassNotFoundException
    {
        if (connect == null)
        {
            Class.forName("com.mysql.jdbc.Driver");
            connect = 
                    DriverManager
                            .getConnection("jdbc:mysql://localhost/test?user=root&password=senha");
        }
        return connect;
    }
    
    public void close() throws Throwable
    {
        if (connect != null) {
            connect.close();
        }
        connect = null;
    }
    
    public PreparedStatement prepareStatement(String sql, boolean lastInsertId) throws SQLException, ClassNotFoundException
    {            
        if (lastInsertId){
            return connect.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        }
        return connect.prepareStatement(sql);
    }
}
Criado 24 de julho de 2016
Ultima resposta 25 de jul. de 2016
Respostas 2
Participantes 3