Is Generic stabbing possible?

Asked

Viewed 256 times

0

Good afternoon I’m studying by object orientation, and in the middle of the studies appeared various patterns and with them a lot of confusion

My doubt is it’s possible to have a generic FACADE. or nothing to see that I’m talking about?

I was watching these videos lessons

Where he creates

  • Bookmaker
  • Interfacelivrodao
  • Bookoid
  • Livrocontroller
  • Book (model)

In his example, it was a register of books, however, I’m making a register of products, where there will be PRODUCTS and BRANDS

I already created the iDao interface using Generic

package br.com.jcom.dao;

import java.util.List;

public interface IDao<T> {

    String getNomeTabela();

    int insert(T... elementos);

    int update(T... elementos);

    int delete(T... elementos);

    //T selectCodigo(String codigo);

    //T select(String sql, String... paramentros);

    List<T> selectAll();

    //List<T> selectAll(String sql, String... paramentros);

}

I have created the models PRODUCTS AND BRANDS

Also tagged

package br.com.jcom.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import br.com.jcom.factory.Conexao;
import br.com.jcom.modelo.Marca;

public class MarcaDao implements IDao<Marca> {

    private String nomeTabela = "Marcas";
    private Connection connection;

    public MarcaDao() {
        this.connection = new Conexao().getConnection();

    }

    @Override
    public String getNomeTabela() {
        return nomeTabela;
    }

    @Override
    public int insert(Marca... elementos) {

        String sql = "INSERT INTO " + nomeTabela + " (marca) VALUES (?)";
        PreparedStatement stmt = null;
        int result = 0;

        for (Marca marca : elementos) {
            try {
                stmt = connection.prepareStatement(sql);
                stmt.setString(1, marca.getMarca());
                result = stmt.executeUpdate();

            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally{
                Conexao.close(connection, stmt, null);
            }
        }

        return result;
    }

    @Override
    public int update(Marca... elementos) {

        String sql = "UPDATE " + nomeTabela + "SET marca = ? WHERE MarcaID = ?";
        PreparedStatement stmt = null;
        int result = 0;

        for (Marca marca : elementos) {
            try {
                stmt = connection.prepareStatement(sql);
                stmt.setString(1, marca.getMarca());
                stmt.setLong(2, marca.getMarcaID());
                result = stmt.executeUpdate();

            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                Conexao.close(connection, stmt, null);
            }
        }

        return result;
    }

    @Override
    public int delete(Marca... elementos) {

        String sql = "DELETE FROM " + nomeTabela + "WHERE MarcaID = ?";
        PreparedStatement stmt = null;
        int result = 0;

        for (Marca marca : elementos) {
            try {
                stmt = connection.prepareStatement(sql);
                stmt.setLong(1, marca.getMarcaID());
                result = stmt.executeUpdate();

            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                Conexao.close(connection, stmt, null);
            }
        }

        return result;
    }

    @Override
    public List<Marca> selectAll() {
        String sql = "SELECT * FROM " + nomeTabela;
        PreparedStatement stmt = null;
        List<Marca> marcas = new ArrayList<Marca>();
        ResultSet rs = null;

        try {
            stmt = connection.prepareStatement(sql);
            rs = stmt.executeQuery();

            while (rs.next()) {
                Marca marca = new Marca();
                marca.setMarcaID(rs.getLong("marcaID"));
                marca.setMarca(rs.getString("marca"));

                marcas.add(marca);

            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            Conexao.close(connection, stmt, rs);
        }
        return marcas;

    }

}

And the score

package br.com.jcom.controller;

import java.util.List;

import br.com.jcom.facade.DaoFacade;
import br.com.jcom.modelo.Marca;

public class MarcaController {

    private DaoFacade marcaFacade;

    public MarcaController() {
        this.marcaFacade = new DaoFacade<Marca>();
    }

    public int addMarca(Marca marca){
        return marcaFacade.insert(marca);

    }

    public int updateMarca(Marca marca){
        return marcaFacade.update(marca);

    }

    public int deleteMarca(Marca marca){
        return marcaFacade.delete(marca);

    }

    public List<Marca> selectMarcas(){
        return marcaFacade.selectAll();

    }
}

Good now in FACADE is that I am not getting very well the logic

package br.com.jcom.facade;

import java.util.List;

import br.com.jcom.dao.IDao;
import br.com.jcom.dao.MarcaDao;

public class DaoFacade<T> {
    @SuppressWarnings("rawtypes")
    private IDao dao;

    public DaoFacade() {
        this.dao = new MarcaDao();

    }

    @SuppressWarnings("unchecked")
    public int insert(T... elementos) {
        return dao.insert(elementos);

    }

    @SuppressWarnings("unchecked")
    public int update(T... elementos) {
        return dao.update(elementos);

    }

    @SuppressWarnings("unchecked")
    public int delete(T... elementos) {
        return dao.delete(elementos);

    }

    @SuppressWarnings("unchecked")
    public List<T> selectAll() {
        return dao.selectAll();

    }

}

When I create the builder

public DaoFacade() {
        this.dao = new MarcaDao();
}

Instead of putting (= new Marcadao();) there is the possibility of passing a generic class to when I = new Productodao, I am confusing everything??

Marcagui > btnSalvar

btnSalvar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Marca marca = new Marca();

            if (Funcoes.validaCampos(panel) == true) {
                marca.setMarca(tfMarca.getText());
            } else {
                JOptionPane.showMessageDialog(null,
                        "Preenchimento de campos (*) obrigatórios");
                return;
            }

            int result = 0;

            if (idMarca == null) {
                result = new MarcaController().addMarca(marca);
            } else {
                marca.setMarcaID(idMarca);
                result = new MarcaController().updateMarca(marca);
                idMarca = null;
            }

            if (result == 1) {
                JOptionPane.showMessageDialog(null, "Concluido");
            } else {
                JOptionPane.showMessageDialog(null, "Erro ao salvar");
            }

            refreshTable();
        }
    });
}
  • That class DaoFacade in the example code is not actually a "facade" as it is not simplifying access to a more complex API. I would recommend reading the full description of the "Pattern" Facade in the original book (Design Patterns).

1 answer

1


For what I see in the code the class DaoFacadeis a generic class, or is prepared for what you want.

By instantiating it you indicate which class it will use.

Your builder will be something like:

public class DaoFacade<T> {
    @SuppressWarnings("rawtypes")
    private T dao;

    public DaoFacade() {
        this.dao = new T();//Não é possível em JAVA - Não compila

    }
    .......
    .......
    .......
}

However, this is not enough, because the methods will have to receive a type that is different for each Dao. Thus, the class DaoFacade, have to have another generic type:

public class DaoFacade<TDao, TEntity> {
    @SuppressWarnings("rawtypes")
    private TDao dao;

    public DaoFacade() {
        this.dao = new TDao();//Não é possível em JAVA - Não compila

    }

    @SuppressWarnings("unchecked")
    public int insert(TEntity... elementos) {
        return dao.insert(elementos);

    }
    .......
    .......
    .......
}

This solution requires creating an instance of the generic parameter, which cannot be done in the usual way: dao = new ();

Thus, the correct way is to make use of Interface IDao and pass Dao on the builder:

public class DaoFacade<T> {
    @SuppressWarnings("rawtypes")
    private IDao dao;

    public DaoFacade(IDao dao) {
        this.dao = dao;

    }
    //O resto do código ficaria igual
    .......
    .......
    .......
}

In this case T would be the entity to process and all methods stay as you have.
To create a new instance of Daofacade:

new DaoFacad<Marca>(new MarcaDao());
  • Exception in thread "AWT-Eventqueue-0" java.lang.Classcastexception: [Ljava.lang.Object; cannot be cast to [Lbr.com.jcom.modelo.Brand; at br.com.jcom.dao.MarcaDao.insert(MarcaDao.java:1)&#xA;at br.com.jcom.facade.DaoFacade.insert(DaoFacade.java:18)&#xA;at br.com.jcom.controller.MarcaController.addMarca(MarcaController.java:18)&#xA; at br.com.jcom.gui.Marcagui$3.actionPerformed(Marcagui.java:140)

  • The problem seems to originate in the class MarcaGUI to which I have no access.

  • Well, you’ve helped me a lot already, I’ll try to solve, Thank you very much

  • Ta giving problem on this line if (idMarca == null) { result = new Marcacontroller(). addMarca(tag); } Else {

  • The variable marca is the type Marca? Mistake is saying she’s the type Object

  • yeah, it’s kind of brand

  • edited the question by putting btnSalvar actionPerformed

  • I can’t find any problem.

  • i tbm not, but returns error. ?

  • upei no mega: https://mega.co.nz/#! Pp1kgahl! e7G1NF6T6zcMPKAdZlHof8Eyw48fppR_SsFJY-2Zw7M has the bank tbm, is sqlserver 2005

  • I can’t help anymore because my IDE is only set up for Android. Ask another question, but try to simplify the code you post.

  • OK, thank you so much then, you’ve helped me enough. :)

  • Oops, you got it.

Show 8 more comments

Browser other questions tagged

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