Data access object - DAO

Asked

Viewed 149 times

1

I’m learning project patterns and applying in a CRUD , within the DAO I can only leave these SQL related code?

    public class UsuarioDAO {
        private Connection con = ConexaoFactory.getConnection();

    public void cadastrar(Usuario usuario) {
        String sql = "insert into usuario(nome, login,senha)values(?,?,?)";
        try(PreparedStatement preparestatement = con.prepareStatement(sql)) {

            preparestatement.setString(1, usuario.getNome()); //substitui o ? pelo dado do usuario
            preparestatement.setString(2, usuario.getLogin());
            preparestatement.setString(3, usuario.getSenha());

            //executando comando sql

            preparestatement.execute();
            preparestatement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public void aleterar(Usuario usuario){
        String sql = "update usuario set nome = ?, login = ?, senha = ? where idusuario = ?";
        try(PreparedStatement preparedStatement = con.prepareStatement(sql)){

            preparedStatement.setString(1, usuario.getNome());
            preparedStatement.setString(2, usuario.getLogin());
            preparedStatement.setString(3, usuario.getSenha());
            preparedStatement.setInt(4, usuario.getIdUsuario());
            preparedStatement.execute();
        }catch(SQLException e){
            e.printStackTrace();
        }
    }

    public void excluir(Usuario usuario){
        String sql = "delete from usuario where idusuario = ?";
        try(PreparedStatement preparedStatement = con.prepareStatement(sql)){
            preparedStatement.setString(1, usuario.getNome());
        }catch(SQLException e){
            e.printStackTrace();
        }
    }

}

1 answer

4


Since I said I’m learning design patterns starting with an observation, you’re leaving out your implementation a key actor in the pattern, the interface. See here.

About what may or may not be within the DAO, it is certainly not only SQL code, very basic and simple for 2 reasons:

1) Dao is not necessarily a database "communicator". Data Access Object deals with access to objects we call data, but it is perfectly possible that this has no database link. An example, an application that handles information from laboratory test results, machines generate xml files, json and other standards (sometimes proprietary), your DAO would never make an sql.

2) Even if it is an application focused on relational databases, your DAO is responsible for making your system work without knowing/accessing the database. This sometimes implies "translations", adaptations, conversions, etc; tasks that also do not require interaction via SQL.

I hope I’ve helped.

  • Thank you, well didactic and explanatory your comment.

Browser other questions tagged

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