Data access object - DAO

1

I am learning design patterns and applying on a CRUD, within DAO can I just leave these code for SQL?

    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();
        }
    }

}
    
asked by anonymous 28.03.2016 / 20:25

1 answer

4

Since you said you are learning design patterns beginning with an observation, you are leaving out of your implementation a key player in the default interface. See here .

On what may or may not be within DAO, it is certainly not just SQL-related code, very basic and simple for 2 reasons:

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

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

I hope I have helped.

    
28.03.2016 / 21:27