* Visite o ALJUG - http://aljug.blogspot.com - Noticias sobre a comunidade java alagoana e do mundo * Visite o blog Mundo Gamificado www.mundogamificado.com.br - E vamos mudar o mundo! *

quinta-feira, 27 de junho de 2013

PieChart Primefaces with Hibernate

Post updated in the new version of Primefaces

  Hello everybody, I come once again leaving a nice tip of programming. Now I'm a bit of time due to the projects and also that realizing a dream of being a teacher, which is rare these days, a college, but teaching database that is also part of my daily life, very good by the way.
 As the title of this post, I will talk about assembling a PieChart with hibernate as soon as notice that we run a little, but I'll do everything for everyone to understand what I'm doing.
  First of all I have two classes, andamento  and status do andamento class at the first have information like: id, comment, status, date and justification, on the other have only id and description. What is the purpose? The goal is to show how the graph gaits exist for each status description, for example, the status "In Progress" has 32 records andamentos,the status "In review" is 5 andamentos records, and so on. So with that we have a scenario to play around with the logic and data, as well as the Data Access Objects will do our research, we first get all the descriptions of existing status in the database :
Code 0:
 public List <Status> Search() {  
     return findAll(Status.class);  
   }  
In class piechart that equals the bean primefaces site´s sample added in the method private void createPieModel () the class variable tempos as follows:
Code 1:
  private List<String> status;
  statusdescricao = stDAO.Search();  
     for (int z = 0; z < statusdescricao.size();z++){  
     status.add(statusdescricao.get(z).getDescricao());  
     }  
  This will be added to this list all the descriptions as you can see below:
Code 2:
 System.out.println("Lista do Status "+status);  
     >> Lista do Status [Em Andamento, Análise, Em avaliação]  

  We conclude the first step, the next step is to bring the figures for these descriptions so it is easy when you know who's the description, because only need a where clause description = String variable. How do the following:
Code 3:
  public int numberTotalOfAndamento(String status) throws NoResultException  

  Making logic with inner join, as in this case I am dealing with two different tables, try the amount of tempos when the id of the status equals the id field in the table id_status progress, for example:
Code 4:
 Query query = manager.createQuery("SELECT count(*) FROM "  
         + "andamento a inner join status s"  
         + " on(a.status = s.id) where s.descricao=:descricao");  
     query.setParameter("descricao", status);  

  In this case ,poses no the function Group by. Done that would add to the method createPieModel the following code snippet:

Code 5:
  for (int i = 0;i < status.size();i++){  
       pieModel.set(status.get(i), andDAO.numberTotalOfAndamento(status.get(i)));  
     }  

  Note that with the list, in this case, with three dice will have to walk, so with each line is we'll get to the method get (index), because the method requires pieModel.set a string and a variable numeral, so in the above code the description "in Progress", represented in code 2, the variable would be the method numberTotalOfAndamento will search and return an integer to compose this method. With that would pieModel.set ("In Progress", 5); Five was the result that was returned.

And to complete the method would look like this:
Code 6:
 private void createPieProcesso() {   
     pieModel = new PieChartModel();   
     statusdescricao = stDAO.Search();   
     for (int z = 0; z &lt; statusdescricao.size();z++){  
     status.add(statusdescricao.get(z).getDescricao());  
     }  
     System.out.println("Lista do Status "+status);  
     for (int i = 0;i &lt; status.size();i++){  
       pieModel.set(status.get(i), andDAO.numberTotalOfAndamento(status.get(i))); 
     }  

And in the JSF page would be represented by the code:
Code 7:
  <p:pieChart value="#{charts.pieModel}" legendPosition="e" fill="false" showDataLabels="true"   
         title="Estatística dos Andamentos" style="width:400px; height:300px" sliceMargin="5" diameter="150" />  

The result will be:
I have helped over this tip up any day.

PieChart PrimeFaces com Hibernate

Post atualizado para versão mais nova do Primefaces 

  Olá pessoal, venho mais uma vez deixar uma bela dica de programação e como sempre dica de JSF2 + Primefaces. Agora estou com um pouco de tempo devido aos projetos e também por que conseguir realizar um sonho de ser professor, o que é raro nos dias atuais, em uma faculdade, mas lecionando Banco de dados que também faz parte do meu dia a dia, muito bom por sinal.
  Como diz o título deste post, vou falar sobre como realizar a montagem de um pieChart com o hibernate, logo já aviso que vamos rodar um pouco, mas vou fazer de tudo para que todos entendam o que estou fazendo.
  Primeiro de tudo tenho duas classes, andamento e status do andamento, na primeira tenho informações como: id,observação, status,data e justificativa, na outra tenho apenas id e descrição. Qual o objetivo? O objetivo é mostra no gráfico quantos andamentos existem para cada descrição do status, por exemplo, o status "Em andamento" possui 32 registros de andamentos o status "Em análise" existe 5 registros de andamentos, e assim por diante. Então com isso temos um cenário para fazer a lógica e brincarmos com os dados, pois bem nos Objetos de acesso a dados(Data Object Acess - DAO´s) faremos nossa pesquisa, primeiro iremos pegar todas as descrições dos status existentes no banco de dados:
Código 0:
 public List <Status> Search() {  
     return findAll(Status.class);  
   }  
Na classe do piechart que é igual ao bean de exemplo do site primefaces adicionei no método private void createPieModel() a variável da classe andamentos da seguinte maneira:
Código 1:
  private List<String> status;
  statusdescricao = stDAO.Search();  
     for (int z = 0; z < statusdescricao.size();z++){  
     status.add(statusdescricao.get(z).getDescricao());  
     }  
Com isso vai ser adicionada neste list todas as descrições existentes como pode ver abaixo:
Código 2:
 System.out.println("Lista do Status "+status);  
     >> Lista do Status [Em Andamento, Análise, Em avaliação]  

Concluímos o primeiro passo, o seguinte passo é trazer os números relativos às essas descrições, então fica fácil quando sabemos quem é a descrição, pois só precisaremos de uma clausula where descricao = váriavel String. Como faremos a seguir:
Código 3:
  public int numberTotalOfAndamento(String status) throws NoResultException  

Fazendo a lógica com inner join, já que neste caso estou lidando com duas tabelas diferentes, procuraremos pela quantidade de andamentos quando o id do status é igual o id do campo id_status na tabela andamento, por exemplo:
Código 4:
 Query query = manager.createQuery("SELECT count(*) FROM "  
         + "andamento a inner join status s"  
         + " on(a.status = s.id) where s.descricao=:descricao");  
     query.setParameter("descricao", status);  

Neste caso dispensaria o Group by. Feito isso adicionaríamos ao método createPieModel o seguinte trecho de código:

Código 5:
  for (int i = 0;i < status.size();i++){  
       pieModel.set(status.get(i), andDAO.numberTotalOfAndamento(status.get(i)));  
     }  

Veja que com a lista, neste caso, com três dados teremos que passear, então com o for pegaremos cada linha com o método get(index), pois o método pieModel.set exige uma string e uma variável numeral , por isso no código acima a descrição "Em Andamento", representado no código 2, seria a variável que o método numberTotalOfAndamento irá procurar e retornar um inteiro para compor esse método. Com isso ficaria pieModel.set("Em Andamento",5); Cinco foi o resultado que foi retornado.

E para concluir o método ficaria desta maneira:
Código 6:
 private void createPieProcesso() {   
     pieModel = new PieChartModel();   
     statusdescricao = stDAO.Search();   
     for (int z = 0; z &lt; statusdescricao.size();z++){  
     status.add(statusdescricao.get(z).getDescricao());  
     }  
     System.out.println("Lista do Status "+status);  
     for (int i = 0;i &lt; status.size();i++){  
       pieModel.set(status.get(i), andDAO.numberTotalOfAndamento(status.get(i))); 
     }  

E na página JSF seria representado pelo código:
Código 7:
  <p:pieChart value="#{charts.pieModel}" legendPosition="e" fill="false" showDataLabels="true"   
         title="Estatística dos Andamentos" style="width:400px; height:300px" sliceMargin="5" diameter="150" />  

O resultado seria:
Espero ter ajudado com mais esta dica, até qualquer dia.