How to implement the DAO pattern in subclasses?

-2

I am developing an application that is about an arms store. I have class Produto with subclasses Arma , Faca and Municao . In this project I'm applying the DAO standard, but I do not quite understand how your subclass application works.

I have 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 in relation to the ArmaDAO class. How should I implement it? Should it extend the ProdutoDAO class? Should the ProdutoDAO class be abstract?

    
asked by anonymous 02.12.2018 / 03:25

1 answer

1

The DAO pattern is one way to separate your data persistence layer from the other layers. I understand what organization can be done the way it thinks best.

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

With this in mind, consider creating a ArmaDAO separated. If you need something from ProdutoDAO , consider using it within ArmaDAO using composition and not inheritance . You did not mention if you're using some dependency injection mechanism, but your class might 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 continue basically as it is.

    
17.12.2018 / 16:39