incompatible types boolean can not be converted to Users

0

I am creating a function to insert new users into the database, but I have this error: "Incompatible types: boolean can not be converted to Users". Does anyone know a way to solve this case:

public String InsertUserCpf(@PathParam("nome")String nome,
        @QueryParam("email") String email,
        @QueryParam("senha") String senha,
        @QueryParam("dtnasc") Date dtnasc,
        @QueryParam("fone") String fone,
        @QueryParam("oab") String oab,
        @QueryParam("cep") String cep,
        @QueryParam("cpf") String cpf)
{
    Usuarios u = new Usuarios();
    u.setNome(nome);
    u.setEmail(email);
    u.setSenha(senha);
    u.setDtnasc(dtnasc);
    u.setFone(fone);
    u.setOab(oab);
    u.setCep(cep);
    u.setCpf(cpf);

    UsuarioDAO dao = new UsuarioDAO();
    u = dao.inserir(u);

    Gson g = new Gson();
    return g.toJson(u);
}

UserDao.java:

public boolean inserir(Usuarios usuario)
    {
        String sql = "INSERT INTO usuarios(nome,email,senha,dtnasc,fone,oab,cep,cpf) VALUES(?,?,?,?,?,?,?,?)";
        Boolean retorno = false;
        PreparedStatement pst = Conexao.getPreparedStatement(sql);
        try {
            pst.setString(1, usuario.getNome());
            pst.setString(2, usuario.getEmail());
            pst.setString(3, usuario.getSenha());
            pst.setDate(4, usuario.getDtnasc());
            pst.setString(5, usuario.getFone());
            pst.setString(6, usuario.getOab());
            pst.setString(7, usuario.getCep());
            pst.setString(8, usuario.getCpf());

            if(pst.executeUpdate()>0)
            {
                retorno = true;
            }



        } catch (SQLException ex) {
            Logger.getLogger(UsuarioDAO.class.getName()).log(Level.SEVERE, null, ex);
            retorno = false;
        }

        return retorno;

    }
    
asked by anonymous 06.10.2017 / 19:58

1 answer

2

Note that you declare a Usuario u and then receive the inserir() method that returns a boolean and not a user. That is, they are different types. Note:

Usuarios u = new Usuarios(); // aqui você instancia
u.setNome(nome);
u.setEmail(email);
u.setSenha(senha);
u.setDtnasc(dtnasc);
u.setFone(fone);
u.setOab(oab);
u.setCep(cep);
u.setCpf(cpf);

UsuarioDAO dao = new UsuarioDAO();
u = dao.inserir(u); // aqui tenta receber em "u" o retorno de dao.inserir() 
                    //que no caso é um boolean (true ou false) e não um Usuario
Gson g = new Gson();
return g.toJson(u);

As I understand it, the insert method returns a boolean that refers to the success of the insert. Soon your logic would look something like this:

boolean sucesso = false;
sucesso = dao.inserir(u);

if (sucesso) { // sucesso ao inserir
    Gson g = new Gson();
    return g.toJson(u);
    //...
}

However, as @Victor Stafusa mentioned, using boolean to return errors is bad programming practice, instead use Exceptions

    
06.10.2017 / 20:03