How to implement the DAO standard in subclasses?

Asked

Viewed 49 times

-2

I’m developing an app that’s a gun store. I own the class Produto with the subclasses Arma, Faca and Municao. In this project I am applying the DAO standard, but I don’t understand very well how its application works in subclasses.

I own the class ProdutoDAO:

public class ProdutoDAO implements GenericDAO<Produto> {

    Connection connection = null;

    @Override
    public void save(Produto produto) throws SQLException {
        try {
            connection = new ConnectionFactory().getConnection();
            String sql = "INSERT INTO PRODUTO(ID, ID_MARCA, DESCRICAO,"
                    + "PESO) VALUES (?, ?, ?, ?);"    ;
            PreparedStatement pstm = connection.prepareStatement(sql);
            pstm.setInt(1, produto.getId());
            pstm.setString(2, produto.getDescricao());
            pstm.setDouble(3, produto.getPeso());
            pstm.execute();
        } catch (SQLException sqle) {
            JOptionPane.showMessageDialog(null, "Erro ao inserir o produto no "
                    + "banco de dados." + sqle.getMessage());
            sqle.printStackTrace();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,
                    "Ocorreu um erro. Contate o suporte.\n" + ex.getMessage());
            ex.printStackTrace();
        } finally {
            connection.close();
        }
    }
}

My question is about class ArmaDAO. How should I implement it? She must extend the class ProdutoDAO? The class ProdutoDAO must be abstract?

1 answer

1


The DAO pattern is a way to separate your data persistence layer from the other layers. I understand that organization can be done the way you think best.

I would not worry about making any kind of inheritance among these classes. The subject is extensive, but inheritance is something that needs to be avoided more than used.

With this in mind, consider creating a ArmaDAO separate. If you need anything from ProdutoDAO, consider using it within the ArmaDAO using composition and non-inheritance. You haven’t mentioned if you’re using any dependency injection mechanism, but your class could look like this:

public class ArmaDAO implements GenericDAO<Arma> {

    @Autowired
    private ProdutoDAO produtoDAO; //usando ProdutoDAO dentro de ArmaDAO, sem herança, com composição

    public void salvarArma(Arma arma) {
         Produto produto = produtoDAO.buscar(); // buscar do ProdutoDAO
         // cria conexão e busca/salvar algo de Arma
    } 

And your Product class would basically continue as it is.

Browser other questions tagged

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