Ajuda com List Java(Resolvido)

Boa tarde galera!. Estou criando um sistema bem simples, apenas usando o console do Eclipse + MySQL.

O que eu fiz até agora:



Bom pelas imagens acima vcs podem ver que eu fiz a parte de cadastro de clientes e ja fiz com que fosse persistido no banco. Até ai tudo bem, o que eu quero fazer agora é Listar esses clientes:

Aqui, após o usuário selecionar a opção 2, gostaria que aparecesse a lista com todos os clientes e seus respectivos dados (id, nome, cpf)

Mas não sei como fazer, li que devo usar o comando List, mas não consegui entender o seu uso.

Alguém poderia me ajudar a implementar este código?

Tente com este exemplo:

/**
     * Metodo com a caracteristica de retornar uma lista de Dados
     *
     * @return List<LocalTransfer>
     * @throws java.sql.SQLException
     */
    public List<LocalTransfer> listarTodosLocal() throws SQLException {
        List<LocalTransfer> localTransfers = new ArrayList<LocalTransfer>();
        try {
            strBuffer = new StringBuffer().append("SELECT *"
                    + "  FROM projetosga.local"
                    + "  ORDER BY nomelocal");
            pstm = abrirconexao.getConexao().prepareStatement(strBuffer.toString());
            rs = pstm.executeQuery();
            while (rs.next()) {
                LocalTransfer localTransfer = new LocalTransfer();
                localTransfer.setId(rs.getShort("idlocal"));
                localTransfer.setNomelocal(rs.getString("nomelocal"));
                localTransfers.add(localTransfer);
            }
        } catch (SQLException ex) {
            logPrincipal(LocalDAO.class).error(">>>>ERROR AO LISTAR LOCAL(listarTodosLocal)", ex);
        } finally {
            rs.close();
            abrirconexao.fecharConexao();
        }
        return localTransfers;
    }
1 curtida

E para imprimir os resultados:

nome_de_sua_classe. listarTodosLocal().stream().forEach(System.out::println);

1 curtida

@Bsi

Minha classe atualmente:

package br.com.fjsistemas.DBController;

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

import br.com.fjsistemas.model.Cliente;

public class DBController {

	private String caminhoDB = "jdbc:mysql://localhost:3306/fjsistemas?serverTimezone=UTC";
	private String usuario = "root";
	private String senha = "fjsistemas";

	@SuppressWarnings("unused")
	private Connection conexao;

	public void abrirConexao() {
		try {
			conexao = DriverManager.getConnection(caminhoDB, usuario, senha);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void criarTabelas() {

		abrirConexao();

		String tabelaClientes = "CREATE TABLE IF NOT EXISTS Clientes"
				+ "(id bigint Primary Key Auto Increment, nome VARCHAR(255) not null, cpf VARCHAR(255) not null)";
		try {
			conexao.prepareStatement(tabelaClientes).execute();

		} catch (SQLException e) {

			e.printStackTrace();
		} finally {
			fecharConexao();
		}
	}

	public void fecharConexao() {

		try {
			if (conexao != null) {

				if (!conexao.getAutoCommit())

					conexao.setAutoCommit(true);
				conexao.close();
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void inserirCliente(Cliente cliente) {

		abrirConexao();

		String inserirCliente = "INSERT INTO Clientes (id, nome, cpf) VALUES (?,?,?)";

		try {

			conexao.setAutoCommit(false);

			PreparedStatement pst = conexao.prepareStatement(inserirCliente);

			pst.setLong(1, cliente.getId());
			pst.setString(2, cliente.getNome());
			pst.setString(3, cliente.getCpf());

			if (pst.execute()) {
				conexao.commit();
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			fecharConexao();
		}
	}
}

Com o seu código

Agora so alterar, para a sua classe de Cliente, para que ele possa gerar depois a lista corretamente.

Onde contiver List. ALterar para Cliente. Coloque aqui a sua classe de Cleinte, certo ?

1 curtida

@Bsi

minha classe cliente

package br.com.fjsistemas.model;

public class Cliente {

	private long id;
	private String nome;
	private String cpf;

	public Cliente() {

	}

	public Cliente(long id, String nome, String cpf) {

		this.id = id;
		this.nome = nome;
		this.cpf = cpf;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getNome() {
		return nome;
	}

	public void setNome(String nome) {
		this.nome = nome;
	}

	public String getCpf() {
		return cpf;
	}

	public void setCpf(String cpf) {
		this.cpf = cpf;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (int) (id ^ (id >>> 32));
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Cliente other = (Cliente) obj;
		if (id != other.id)
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "\n=============" + "\nCliente: " + "\nID: " + id + "\nNome: " + nome + "\nCPF: " + cpf
				+ "\n============= " + "\n " + "\nCliente Cadastrado com Sucesso!";
	}

}

@Bsi vc disse que onde está List, altero para Cliente…

então essa primeira linha por exemplo:

List<LocalTransfer> localTransfers = new ArrayList<LocalTransfer>();

ficaria

Cliente<LocalTransfer> localTransfer = new ArrayList<LocalTransfer>();

eu achei que na verdade ficaria assim:

List<Cliente> listaClientes = new ArrayList<Cliente>();


    public List<Cliente> LISTARTODOSCLIENTES() throws SQLException {
        List<Cliente> clientes = new ArrayList<Cliente>();
        PreparedStatement  pstm =null;
        ResultSet rs;
        try {
        StringBuffer  strBuffer = new StringBuffer().append("SELECT *"
                    + "  FROM cliente"
                    );
       pstm = conexao.prepareStatement(strBuffer.toString());
            rs = pstm.executeQuery();
            while (rs.next()) {
               Cliente cliente = new Cliente();
               cliente.setId(rs.getShort("idcliente"));
                cliente.setNome(rs.getString("nome"));
                cliente.setCpf(rs.getString("cpf"));
                clientes.add(cliente);
            }
        } catch (SQLException ex) {
           System.out.print(ex);
        } finally {
            pstm.close();
            rs.close();
            fechar a sua conexao ou nao dependendo do que necessita
        }
        return clientes;
    }
1 curtida

@Bsi fiz como vc me passou, mas ainda não deu certo

Minha classe DBController com o metodo lista:

package br.com.fjsistemas.DBController;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import br.com.fjsistemas.model.Cliente;

public class DBController {

	private String caminhoDB = "jdbc:mysql://localhost:3306/fjsistemas?serverTimezone=UTC";
	private String usuario = "root";
	private String senha = "fjsistemas";

	@SuppressWarnings("unused")
	private Connection conexao;

	public void abrirConexao() {
		try {
			conexao = DriverManager.getConnection(caminhoDB, usuario, senha);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void criarTabelas() {

		abrirConexao();

		String tabelaClientes = "CREATE TABLE IF NOT EXISTS Clientes"
				+ "(id bigint Primary Key Auto Increment, nome VARCHAR(255) not null, cpf VARCHAR(255) not null)";
		try {
			conexao.prepareStatement(tabelaClientes).execute();

		} catch (SQLException e) {

			e.printStackTrace();
		} finally {
			fecharConexao();
		}
	}

	public void fecharConexao() {

		try {
			if (conexao != null) {

				if (!conexao.getAutoCommit())

					conexao.setAutoCommit(true);
				conexao.close();
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void inserirCliente(Cliente cliente) {

		abrirConexao();

		String inserirCliente = "INSERT INTO Clientes (id, nome, cpf) VALUES (?,?,?)";

		try {

			conexao.setAutoCommit(false);

			PreparedStatement pst = conexao.prepareStatement(inserirCliente);

			pst.setLong(1, cliente.getId());
			pst.setString(2, cliente.getNome());
			pst.setString(3, cliente.getCpf());

			if (pst.execute()) {
				conexao.commit();
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			fecharConexao();
		}
	}

	public List<Cliente> LISTARTODOSCLIENTES() throws SQLException {
		List<Cliente> clientes = new ArrayList<Cliente>();
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			StringBuffer strBuffer = new StringBuffer().append("SELECT *" + "  FROM cliente");
			pstm = conexao.prepareStatement(strBuffer.toString());
			rs = pstm.executeQuery();
			while (rs.next()) {
				Cliente cliente = new Cliente();
				cliente.setId(rs.getShort("id"));
				cliente.setNome(rs.getString("nome"));
				cliente.setCpf(rs.getString("cpf"));
				clientes.add(cliente);
			}
		} catch (SQLException ex) {
			System.out.print(ex);
		} finally {
			pstm.close();
			rs.close();

		}
		return clientes;
	}
}

Minha classe App (view)

package br.com.fjsistemas.view;

import java.sql.SQLException;
import java.util.Scanner;

import br.com.fjsistemas.DBController.DBController;
import br.com.fjsistemas.model.Cliente;
import br.com.fjsistemas.util.CadastroCliente;
import br.com.fjsistemas.util.MenuCadastroCliente;
import br.com.fjsistemas.util.MenuPrincipal;

public class App {

	@SuppressWarnings("unused")
	private static final String UNUSED = "unused";
	@SuppressWarnings("unused")
	private static final String RESOURCE = "resource";

	public static void main(String[] args) {

		Cliente cliente = new Cliente();

		DBController db = new DBController();

		Scanner sc = new Scanner(System.in);

		MenuPrincipal menu = new MenuPrincipal();

		int opcao, opcao2;

		char resposta = 0;

		do {
			menu.getClass();
			menu.MenuSecundario();
			opcao = sc.nextInt();

			if (opcao == 1) {

				MenuCadastroCliente menuCliente = new MenuCadastroCliente();
				menuCliente.getClass();
				opcao2 = sc.nextInt();

				do {
					if (opcao2 == 1) {

						CadastroCliente cadCliente = new CadastroCliente();

						cadCliente.CadastroClienteNome();
						cliente.setNome(sc.next());

						cadCliente.CadastroClienteCPF();
						cliente.setCpf(sc.next());

						sc.nextLine();

						db.inserirCliente(cliente);

						System.out.println(cliente.toString());
						menuCliente.perguntaFinal();
						resposta = sc.nextLine().charAt(0);

					}
				} while (resposta == 'Y' || resposta == 'y');

			}
			
			if(opcao == 2) {
				try {
					db.LISTARTODOSCLIENTES().stream().forEach(System.out::println);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		} while (opcao != 4);
		System.out.println("\nAgradecemos por utilizar nosso programa.");
		sc.close();
	}

}

Resultado:

Coloca para depurar o seu codigo na linha correspondente ao metodo. Verifique que o ID relacionado ao seu é do tipo Long, e o meu está como o tipo Short. Dependedo, você tem que alterar conforme a sua necessidade.

Primeiro verifique se cada “set” corresponde a cada variável da sua classe Cleinte, certo ?

Eu percebi que o select seu esta com o seguinte schema: ```
fjsistemas

Então, altere o select de: ```
"SELECT *  FROM cliente"

> Para: SELECT * FROM fjsistemas.clientes;

1 curtida

@Bsi

realmente um set estava com short, alterei para long, e tbm alterei o select…mas o comportamento do sistema continua o mesmo, quando selecio a opção 2, que é referente a lista, ele simplesmente ignora a ação e volta para o menu

Entendo.

Tente deixar o mais limpo o possível o seu método para imprimir.

Primeiro coloque para depurar o código em si. E veja onde ela retorna os valores, ok?!

Tente deixar a sua classe mais limpa.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.unit.preconceito;

import java.util.ArrayList;
import java.util.Collections;
import static java.util.Collections.list;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

/**
 *
 * @author Matheus
 */
public class Principal {
    
    /*envia mensagem para tela informando que a opcao e invalida*/
        public static void mensagem(int opcao) throws Exception
        {

            try
            {

//                if (opcao == null || null == opcao)
//                {
//                    System.out.println("OPCAO INVALIDA. TENTE NOVAMENTE!!!\n\n\n");
//                    Thread.sleep(2000);
//                    return;
//                }

//                int op = Integer.parseInt(opcao);
               

                if (opcao < 0 || opcao > 5)
                {
                    System.err.println("OPCAO INVALIDA. TENTE NOVAMENTE!!!\n\n\n");
                    Thread.sleep(2000);
                }
                else

                if (opcao == 0)
                {
                    System.out.println("\tBYEE!!!\n\n\n");
                    System.exit(0);
                }
                
            }
            catch (Exception ex)
            {
                System.out.println("O FORMATO DOS CARACTERES NAO EXISTENTE.\n\t TENTE NOVAMENTE\n\n\n"+ex.getMessage());
            }


        }
    
       /*metodo para fazer devida escolhas de 0 : SAIR e 1: COPIAR ARQUIVOS para a pasta bin do Workbank*/
        public static void escolhas()
        {
            
            System.out.println("*********************PRECONCEITO*****************");
            System.out.println("*\t\t\tUNIT\t\t\t*");
            System.out.println("*************************************************");
            System.out.println("*\t0: SAIR\t\t\t\t\t*");
            System.out.println("*\t1: CADASTRAR\t\t\t\t*");
            System.out.println("*\t2: LISTAR OCORRENCIAS \t\t\t*");
            System.out.println("*\t3: LISTAR ENVOL. COM SUAS OCORRENCIAS\t*");
            System.out.println("*\t4: LISTAR PORCENTAGEM DE OCORRENCIAS\t*");
            System.out.println("*\t5: LISTAR LOCALIDADE DE OCORRENCIAS\t*");
            System.out.println("*********************PRECONCEITO*****************");
            System.out.print("Por Favor selecione uma opção [0-5]:");
        }
    
    
    public static void main(String [] unitargs) throws Exception {
        Scanner scan = new Scanner(System.in);
    
    PreconceitoTransfer _preconceitoTransfer     = new PreconceitoTransfer();//cria um atribtuo(instancia) da classe que contem getters e setters
    List<PreconceitoTransfer> _lista             = new ArrayList<PreconceitoTransfer>(); //arraylist para pegar tudo
    List<String> nomes                           = new ArrayList<String>();// atributo de nomes

        
        String ocorrenciapreconceito                = null;//atributo para identificar o tipo de preconceito
        String localocorrencia                      = null;//atributo para identificar o local da ocorrencia
        String descricao                            = null;//atributo para identificar a minha ocorrencia

        int op = -1;
        escolhas();
        op=scan.nextInt();
        mensagem(op);
          
        PreconceitoTransfer pre = new PreconceitoTransfer(ocorrenciapreconceito,localocorrencia,descricao,nomes);//cria uma outra instancia para nao perder os valores passados que serao depois inseridos e comparados em cada condicao onde tenha map
       
        while(op!=0){
  
            if(op==1){
                
                System.out.println("Informe ocorrencia preconceito:");
                ocorrenciapreconceito = scan.next().toUpperCase();
                scan.nextLine();
                System.out.println("Informe local acontecimento:");
                localocorrencia = scan.nextLine().toUpperCase();
                System.out.println("Informe descricao preconceito:");
                descricao = scan.nextLine().toUpperCase();
                System.out.println("Informe nome da pessoa:");
                nomes.add(scan.nextLine().toUpperCase());

                _preconceitoTransfer.setOcorrenciapreconceito(ocorrenciapreconceito);
                _preconceitoTransfer.setLocalocorrencia(localocorrencia);
                _preconceitoTransfer.setDescricao(descricao);
                _preconceitoTransfer.setNomes(nomes);
                
                pre = new PreconceitoTransfer(_preconceitoTransfer.getOcorrenciapreconceito(),_preconceitoTransfer.getLocalocorrencia(),_preconceitoTransfer.getDescricao(),_preconceitoTransfer.getNomes());
                _lista.add(pre);
                
            }
          
            if(op==2){
                    Map<String, Integer> _contem                 = new TreeMap<String, Integer>();//criacao de map para identificacao de chave,valor
                    for (PreconceitoTransfer nome : _lista) {
        
                        if (!_contem.containsKey(nome.getOcorrenciapreconceito())){
                            _contem.put(nome.getOcorrenciapreconceito(), 0);
                        }
                            _contem.put(nome.getOcorrenciapreconceito(), _contem.get(nome.getOcorrenciapreconceito()) + 1);
                    }

                    for (Map.Entry<String, Integer> entry : _contem.entrySet()) {
                        if(entry.getValue()>=5){    
                            System.out.println(entry.getKey()+":"+ entry.getValue());
                        }
                    }
            }
            
            if(op==3){
                        

               Map<String, Integer> _contem                 = new TreeMap<String, Integer>();//criacao de map para identificacao de chave,valor   
               for (PreconceitoTransfer nome : _lista) {
        
                        if (!_contem.containsKey(nome.getOcorrenciapreconceito())){
                            _contem.put(nome.getOcorrenciapreconceito(), 0);
                        }
                            _contem.put(nome.getOcorrenciapreconceito(), _contem.get(nome.getOcorrenciapreconceito()) + 1);                                   
                        }
                        
                        for (Map.Entry<String, Integer> entry : _contem.entrySet()){
                             System.out.println("["+entry.getKey()+"]:\n");  
                        }
                        for (String nome:nomes) {
                            System.out.println(""+nome);
                        }
                        
                             
                    System.out.println("\n");
            }
            
 
            
            if(op==4){
                
                    Map<String, Integer> _contem                 = new TreeMap<String, Integer>();//criacao de map para identificacao de chave,valor
                    for (PreconceitoTransfer nome : _lista) {
        
                        if (!_contem.containsKey(nome.getOcorrenciapreconceito())){
                            _contem.put(nome.getOcorrenciapreconceito(), 0);
                        }
                            _contem.put(nome.getOcorrenciapreconceito(), _contem.get(nome.getOcorrenciapreconceito()) + 1);
                    }
                    int totalporcentagem = 0;
                    for (Map.Entry<String, Integer> entry : _contem.entrySet()) {
                            totalporcentagem=(entry.getValue()*100)/_lista.size();
                            System.out.println("["+entry.getKey()+"]:"+totalporcentagem);
                        
                    }     
                
            }
                   
                 
            if(op==5){
                
                    Map<String, Integer> _contem                 = new TreeMap<String, Integer>();//criacao de map para identificacao de chave,valor
                    for (PreconceitoTransfer nome : _lista) {
        
                        if (!_contem.containsKey(nome.getLocalocorrencia())){
                            _contem.put(nome.getLocalocorrencia(), 0);
                        }
                            _contem.put(nome.getLocalocorrencia(), _contem.get(nome.getLocalocorrencia()) + 1);
                    }

                    for (Map.Entry<String, Integer> entry : _contem.entrySet()) {    
                            System.out.println(entry.getKey()+":"+ entry.getValue());
                    }
            }
        
            escolhas();
            op=scan.nextInt();
            mensagem(op);
            
        }
        
        
    }
}

Analise colocando os seus métodos, certo ?

1 curtida

@Bsi só estava faltando abrir a conexao com o banco…muito obg por sua ajuda