Return BD data using List/Arraylist - Java

Asked

Viewed 5,148 times

2

I have a problem, I set up a dynamic table in Postgresql and I need to print the lines of it, performing a method in Java, whose beginning is already pre-set. That would be with a List simple with start and end dates as a parameter.

Follow the pre-established code:

public void printReport(Date initialDate, Date endDate) {
          List<Sale> sales = getSales(initialDate, endDate);
          ...
}

The output needs to be for example: Loja01;100;100;50;0;250. But I don’t know how to access the column and the store row by going through all the data.

I already have a method that prints as follows. Example: Loja01 with 3 sales (100,00 visa; 55,00 visa; 200,00 master) will print: Loja01; visa; 155// on the other line Loja01;master;200; Follows code in java:

    public void printReport (Date initialDate, Date endDate){

        List<Sale> sales = getSales (initialDate, endDate);

        for (Sale s:sales){

            Store st = s.getStore(); // Recupera a Loja

            CreditCard cc = s.getCreditCard(); // Recupera o Cartão

            System.out.println(st.getNome() + ";" + cc.getName() + ";" + s.getValor());
        }
}

Imagem dos registros da tabela

Tabelas criados no BD

3 answers

1

First, we start with a class that represents a sale. This class is immutable, see the reasons in that other answer of mine:

public final class Sale {
    private final String storeNome;
    private final int visa;
    private final int master;
    private final int diners;
    private final int amex;

    public Sale(String storeName, int visa, int mster, int diners, int amex) {
        this.storeName = storeName;
        this.visa = visa;
        this.master = master;
        this.diners = diners;
        this.amex = amex;
    }

    public String getStoreNome() {
        return storeNome;
    }

    public int getVisa() {
        return visa;
    }

    public int getMaster() {
        return master;
    }

    public int getDiners() {
        return diners;
    }

    public int getAmex() {
        return amex;
    }

    public int getTotal() {
        return visa + master + diners + amex;
    }

    @Override
    public String toString() {
        return storeNome + ";"
                + visa + ";" + master + ";" + diners + ";" + amex + ";" + getTotal();
    }
}

That done, I’ll borrow of that other answer a class representing connection parameter:

import java.sql.DriverManager;
import java.sql.SQLException;

public class ParametrosDeConexao {

    private final String url;
    private final String usuario;
    private final String senha;

    public BaseDeDados(String url, String usuario, String senha) {
        this.url = url;
        this.usuario = usuario;
        this.senha = senha;
    }

    public Connection conectar() throws SQLException {
        return DriverManager.getConnection(url, usuario, senha);
    }
}

You will have to create an instance of this class and keep it somewhere (it may be a static variable) in order to connect to the database. The URL, user and password setting will depend on what your database will be.

Finally, we can make the class that accesses the database:

public class SaleDAO {

    private static final String SALES_BY_DATES_SQL = ""
            + "SELECT store_nome, visa, master, diners, amex "
            + "FROM Sale "
            + "WHERE date >= ? AND date <= ?";

    private final ParametrosDeConexao params;

    public SaleDAO(ParametrosDeConexao params) {
        this.params = params;
    }

    public List<Sale> getSales(Date startDate, Date endDate) {
        try (
            Connection c = params.conectar();
            PreparedStatement ps = c.prepareStatement(SALES_BY_DATES_SQL);
        )
        {
            ps.setDate(1, startDate);
            ps.setDate(2, endDate);
            try (ResultSet rs = ps.executeQuery()) {
                List<Sale> sales = new ArrayList<>();
                while (rs.hasNext()) {
                    Sale s = new Sale(
                            rs.getString("store_nome"),
                            rs.getInt("visa"),
                            rs.getInt("master"),
                            rs.getInt("diners"),
                            rs.getInt("amex"));
                    sales.add(s);
                }
                return sales;
            }
        }
    }
}

The code above worries about close resources properly with the help of the compiler.

The above code assumes that the Date also contains the time information. Therefore if you put that the endDate for no dia 10/10/2018 00:00:00, he will not take the sale made at 09:00 of the day 10/10/2018. If you don’t want this behavior, leave a comment here on that answer. An alternative to that would be work with the class LocalDate or LocalDateTime.

Note that I have omitted the field total in SQL and class Sale. The reason is that it is always the sum of visa, master, diners and amex, and therefore would not need to be read from the database nor stored in memory. If that is really the case, you could even remove it from the table.

  • So, I read your suggestions and really absorbed more knowledge. I am only in doubt as to the attributes of the sale class, I can’t pick up the identifier of each card and the Bank’s own Internet store? I will edit the question and put my tables.

  • @Lucasesbegue Which SELECT you have assembled by joining the tables Sale, CreditCard and Store? In particular, I want to understand where the fields came from visa, master, diners and amex and their respective values.

  • The following is a BD link in SQL Fiddle: http://sqlfiddle.com/#! 17/5c3eb/1. I set up a select that uses a postgresql function, 'jsonb_object_agg', I tried it with Crosstab, but I couldn’t.Well the fields came from the Insert itself in their respective tables.

  • Any suggestions? I don’t know how to use the three tables in java.

0

    public List<Sale> getSales (Date startDate, Date endDate  ){

        Conection con = //de alguma forma vc pega conexao com o banco

        Statement stmt = con.createStatement();

         List<Sale> sales = new ArrayList<>();

        //aqui você recebe um objeto ResultSet com todos os elementos
        //da tabela ales:

        ResultSet rs = stmt.executeQuery("SELECT * FROM sales s WHERE  s.date BETWEEN ? AND ? ");

           stmt.setDate(1, new java.sql.Date( startDate.getTime() )) ;
           stmt.setDate(2, new java.sql.Date(endDate.getTime() ));

        //para percorrer o resultset, faca:

        while(rs.next()) {

           Sale sale = new Sale();

          //pega o valor da coluna nome, de cada linha:
          sale.setStoreName ( rs.getString("store_nome") ) ;
          sale.setVisa( rs.getString("visa") );
          sale.setMaster( rs.getString("master") ) ;
          sale.setDiners ( rs.getString("diners") );
          sale.setAmex ( rs.getString("amex") );
          sale.setTotal ( rs.getDouble("total") );

          sales.add(sale);

    }

   return  sales;

 }// end getSales

CLASS

public class  Sale {

         //por questões didáticas coloquei como String a maioria.

          private String storeName;
          private String visa ;
          private String master ;
          private String diners;
          private String amex ;
          private Double total;


     //getts e setts

}

METHOD:

public void printReport(Date initialDate, Date endDate) {
          List<Sale> sales = getSales(initialDate, endDate);//chamando getSales
          ...
}
  • Recommended reading: https://answall.com/q/172909/132

  • @LR10, I use three tables in BD and need to create their respective class in java, not just put everything in sale. I just need to encode the printReport method, with a simple print, but I don’t know how to access the information.

  • then you have to make a VO with the fields you want to appear in the report and then make an SQL that returns the data you want and popular it in your VO.

  • @LR10 So my task is just to assemble the method, taking into account that all classes (Sale, Store, Credit_card, Bank access etc...are already ready, I need to create the method to print as I put in the question. I’ve never seen VO, I’m going to a research

  • You want a method that prints itself report?

  • This @LR10, is the continuation that completes the printReport method. Taking into account my BD. And taking into account that all the rest of the program is perfect.

  • I have a method that prints as follows: Example: Loja01 with 3 sales(100,00 visa; 55,00 visa; 200,00 master) will appear in the report like this: Loja01;visa;155; Loja01;Master; 200; I edited the question and added the method that prints in this way.

  • @Lucasesbegue this issue you made is another problem?

  • No @Articuno, the method works. I just edited to inform what I have at the moment, and what I’m trying to do. What is to print for example:Loja01;100;100;50;0;250. Taking into account the photo of the table I posted in the question.

Show 4 more comments

0

To print data separated by ;, considering the data search of the database made by the colleague above After Voce searched the data from your database or another, E has the data in a collection in java (Arraylist), just iterate the array like this:

      public void printReport(Date initialDate, Date endDate) {
        List<Sale> sales = getSales(initialDate, endDate);//chamando getSales
        StringBuilder sb = new StringBuilder();
        for(Sales sale: sales){
        sb.append(sale.getStoreName() + ";" + sale.getVisa() + ";"+sale.getMaster() + ";" + sale.getDiners() + ";" + sale.getAmex() + ";" + sale.getTotal());


    }
}
System.out.println(sb.toString());

can get even easier if you overwrite the toString method of the Sales class

 @override
 public String toString(){
  return storeName+";"+visa+";"+master+";"+dinners+";"+amex+";"+total;
 }

So no for Voce would do:

for(Sales sale: sales){
   sb.append(sale.toString());


  }

Edit: Consider the Store object as an attribute of the Sale class (Code snippets of other answers in this question)

Store class.

public class Store{
    private int id;
    private String name;
    //gets and sets
}

Sale class

public class  Sale {

     //por questões didáticas coloquei como String a maioria.

      private Store store;
      private String visa ;
      private String master ;
      private String diners;
      private String amex ;
      private Double total;


 //getts e setts
 } 

An example of Select that would bring the BD data

private static final String SALES_BY_DATES_SQL = ""
        + "SELECT store.name store_name, store.id store_id, visa, master, diners, amex "
        + "FROM Sale, Store "
        + "WHERE date >= ? AND date <= ?"
        + " and sale.store_id = store.id";

Method retrieving data from BD

public List<Sale> getSales(Date startDate, Date endDate) {
    try (
        Connection c = params.conectar();
        PreparedStatement ps = c.prepareStatement(SALES_BY_DATES_SQL);
    )
    {
        ps.setDate(1, startDate);
        ps.setDate(2, endDate);
        try (ResultSet rs = ps.executeQuery()) {
            List<Sale> sales = new ArrayList<>();
            while (rs.hasNext()) {
                Sale s = new Sale(
                        //carregando o objeto store.
                        Store store = new Store();
                        store.setId(rs.getInt("store_id"));
                        store.setName(rs.getString("store_name"));
                        sale.setStore(store);

                        rs.getInt("visa"),
                        rs.getInt("master"),
                        rs.getInt("diners"),
                        rs.getInt("amex"));
                sales.add(s);
            }
            return sales;
        }
    }
}

Then to create the layout:

for(Sales sale: sales){
        sb.append(sale.getStore().getName() + ";" + sale.getVisa() + ";"+sale.getMaster() + ";" + sale.getDiners() + ";" + sale.getAmex() + ";" + sale.getTotal());


}

or:

 @override
 public String toString(){
  return getStore().getName()+";"+visa+";"+master+";"+dinners+";"+amex+";"+total;
 }

Edit: Whereas the data is already coming right from the database:

method that formats the print:

public StringBuilder formatarLayout(ArrayList<Sales> sales){
StirngBuilder sb = new StringBuilder();
    for(Sales sale: sales){
        sb.append(sale.getStore().getName() + ";" + sale.getVisa() + ";"+sale.getMaster() + ";" + sale.getDiners() + ";" + sale.getAmex() + ";" + sale.getTotal());


    }

    return sb;

}

printReport method

public void printReport(Date initialDate, Date endDate) {
          List<Sale> sales = getSales(initialDate, endDate);
          //isso ja retorna seus dados formatados
          String  layout = formatarLayout(sales).toString();
          // agora pode fazer o que quiser com eles
}
  • Yes, this was really the closest I’m trying to get.However "storeName" is not part of the table Sale qie moving to java would be the classes. That’s my biggest problem and doubt, the only relationship they have is the id’s. I edited the question and added the tables and relations.

  • Creates within the Sales Store object class, which contains the id and name. In your select, which returns the database data, bring the Stores information, doing the Join by Id. In the method that puts this in the arrayList, loads the Store object, which is an attribute of the Sale class., sale.getStore().getName()

  • Yes, that’s right. But then could I use the pre-established code? And I don’t understand why I need to declare the names of the cards as an attribute.

  • then, the attributes are so that you can recover the database data and use them in java, as Voce posted in your question: Loja01;100;100;50;0;250 the values 100, 100 50 are gurdata values in the visa column, master Diner

  • Okay, I got it!!! But with this I could no longer use the -- 'public void printReport(Date initialDate, Date endDate) brody###Xa; List<Sale> Sales = getSales(initialDate, endDate); ... } ?

  • yes, in the answer, I put this inside the printReport method

  • If I don’t want to use the formatting methodLayout, can I use the pre-set printReport method and do the stringbuilder instance and for, and then print with System.out.println(Sb.toString());? Would be correct?

  • yes, I created an example method only, Voce can use as Voce find better in your environment

  • Yes, I understood. Another question, in this example I would use the Credit_card class? In this table in the BD are the names of the cards(visa, master, Diners, Amex).

Show 4 more comments

Browser other questions tagged

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