Doubt validation of Cpf before inserting in the bank

Asked

Viewed 333 times

2

In my class SocioDAO I have the method salvarSocio() which will be saved in the database. In my class DadosUsuario I have the information that needs to be recorded in the bank in case cadastrarUsuario(). How to proceed to validate CPF?

I didn’t want to put validation into my method cadastrarUsuario() because not the same shouldn’t get too big.

public class SocioDAO {

    public void salvarSocio(Socio socio) throws SQLException {
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT INTO socio ");
        sql.append("(nome, telefone, ddd, email, cpf) ");
        sql.append("VALUES (?, ?, ?, ?, ?) ");

        Connection conexao = ConexaoFactory.conectar();

        PreparedStatement comando = conexao.prepareStatement(sql.toString());

        comando.setString(1, socio.getNome());
        comando.setInt(2, socio.getTelefone());
        comando.setInt(3, socio.getDdd());
        comando.setString(4, socio.getEmail());
        comando.setString(5, socio.getCpf());

        comando.executeUpdate();

    }



public class DadosUsuario {

    static Scanner scan = new Scanner(System.in);

    public void cadastrarUsuario() {

        Socio cadastrarUser = new Socio();

        System.out.println("Informe um nome: ");
        cadastrarUser.setNome(scan.nextLine());

        System.out.println("Informe um telefone: ");
        cadastrarUser.setTelefone(scan.nextInt());

        System.out.println("Informe o DDD: ");
        cadastrarUser.setDdd(scan.nextInt());

        System.out.println("Informe o email: ");
        cadastrarUser.setEmail(scan.next());

        System.out.println("Informe o cpf: ");
        cadastrarUser.setCpf(scan.next());

        SocioDAO dao = new SocioDAO();

        try {
            dao.salvarSocio(cadastrarUser);
            System.out.println("USUÁRIO CADASTRADO COM SUCESSO.");
        } catch (SQLException e) {
            System.out.println("ERRO AO CADASTRAR USUÁRIO.");
            //e.printStackTrace();
        }

    }

1 answer

3

Since you don’t have a business layer and access the DAO directly, you should put the validation inside the DAO, which finding some problem, release an exception. Placing inside the DAO, anywhere you instantiate it, will ensure that the data is being validated.

In a more serious application, we never access DAO directly. We always go through a business layer that serves precisely to make this validation, getting Service (with its business rule and validation) -> DAO

Take the opportunity to take a look at this answer also, the subject can be quite long.

Edit: simple example with business layer

public class SocioService { // Tem pessoas que preferem SocioBusiness

    private SocioDAO socioDAO;

    public SocioService() {
        socioDAO = new SocioDAO();
    }

    public void inserir(Socio socio) throws ServiceException { // inserir ou adicionar deixa claro que é "criação" de registro.

        if (socio.getNome() == null || socio.getNome().trim().length()) {
            throw new ServiceException("Nome não pode estar vazio");
        }

        // ... outras validacoes

        socioDAO.salvarSocio(socio); // cuidado com o adjetivo salvar, ele pode deixar a pessoa que chama em duvida, se estiver trabalhando em equipe, a pessoa iria querer ver o fonte para saber se aqui está sendo inserido ou atualizando um registro.
    }
}

public class ServiceException extends Exception {

    public ServiceException(String mensagem) {
        super(mensagem);
    }
}
  • And how could I create this other layer... could give me a touch?

  • although not the scope of your question, I added. If you don’t also have a way to recover from a Sqlexception, create an exception of Runtime (not checked) yours, and launch it from within the DAO. It also has other important details on how not to handle transactions within a DAO method, but now it’s not the case :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.