简体   繁体   English

来自数据库的PrimeFaces图表

[英]PrimeFaces Chart From Database

I already have a CRUD webApp (JSF+EJB+JPA) and I'm trying to develop a chartBean class so I can use it in the View layer. 我已经有一个CRUD webApp(JSF + EJB + JPA),并且我正在尝试开发一个chartBean类,以便可以在View层中使用它。 The data to be rendered (through Primefaces-4 BarChart) should be read from a database. 应该从数据库中读取要渲染的数据(通过Primefaces-4 BarChart)。

In the Chart, I have 2 chartSeries to be displayed: 在图表中,我有2个chartSeries要显示:

  • chartSeries1: the employeeGoal -> the 'valor' float column mapped in the Orc entity class below; chartSeries1:employeeGoal->在下面的Orc实体类中映射的'valor'浮动列;
  • chartSeries2: the employeeAccomplished -> the 'Realizado' integer column mapped in the hr_capacit30h entity class below. chartSeries2:employeeAccomplished->在下面的hr_capacit30h实体类中映射的'Realizado'整数列。

The X-Axis should display the Hours (based on the 'chartSeries2' values above). X轴应显示小时(基于上面的“ chartSeries2”值)。

The Y-axis should display the employeeName (the 'nome' string field in the hr_capacit30h entity class below). Y轴应显示employeeName(下面的hr_capacit30h实体类中的'nome'字符串字段)。

Does anyone knows how to develop the createCartesianChartModel() method below to be used in a jsf page? 有谁知道如何开发以下要在jsf页面中使用的createCartesianChartModel()方法?

The ChartBean class: ChartBean类:

//imports ommited

@ManagedBean
@RequestScoped
public class hrCapacitChart {

    private Map<Integer, Map<String, Number>> HrCapacitFuncis = new HashMap<Integer, Map<String, Number>>();
    private double totalHoras;
    private CartesianChartModel cartesianChartModel;

    @EJB
    private HrCapacit30hFacade hcf;

    public hrCapacitChart() {
    }

    @PostConstruct
    private void initialize() {
        cartesianChartModel = new CartesianChartModel();
        createCartesianChartModel();
    }

    public CartesianChartModel getCartesianChartModel() { 
        return cartesianChartModel;
    }

    private void createCartesianChartModel() { 
        List<HrCapacit30h> hrCapacit30h = hcf.findAll();
    // THIS IS THE METHOD/(Managed Bean property) TO BE DEVELOPED
    }
}

The HrCapacit30h entity class (related to chartSeries2 an Y-axis / see description above): HrCapacit30h实体类(与chartSeries2的Y轴相关/请参见上面的描述):

@Entity
@Table(name = "hr_capacit30h", catalog = "DIAGE", schema = "atb")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "HrCapacit30h.findAll", query = "SELECT h FROM HrCapacit30h h"),
    @NamedQuery(name = "HrCapacit30h.findByMatricula", query = "SELECT h FROM HrCapacit30h h WHERE h.hrCapacit30hPK.matricula = :matricula"),
    @NamedQuery(name = "HrCapacit30h.findByNome", query = "SELECT h FROM HrCapacit30h h WHERE h.nome = :nome"),
    @NamedQuery(name = "HrCapacit30h.findByRealizado", query = "SELECT h FROM HrCapacit30h h WHERE h.realizado = :realizado"),
    @NamedQuery(name = "HrCapacit30h.findByDtMov", query = "SELECT h FROM HrCapacit30h h WHERE h.hrCapacit30hPK.dtMov = :dtMov")})
public class HrCapacit30h implements Serializable {
    private static final long serialVersionUID = 1L;
    @EmbeddedId
    protected HrCapacit30hPK hrCapacit30hPK;
    @Size(max = 100)
    @Column(name = "Nome")
    private String nome;
    @Column(name = "Realizado")
    private Integer realizado;
    @JoinColumn(name = "codUOR", referencedColumnName = "cod_UOR")
    @ManyToOne(optional = false)
    private UpbDeps codUOR;
    @JoinColumn(name = "status", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Status status;
    @JoinColumn(name = "idOrc", referencedColumnName = "id")
    @ManyToOne
    private Orc idOrc;
    @JoinColumn(name = "idDiv", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private DivDeps idDiv;

    public HrCapacit30h() {
    }

//getters/setters/equals/hashCode ommited    
}

The Entity Orc class (related to chartSeries1 / see description above):: 实体Orc类(与chartSeries1 /相关)/:

//imports ommited

@Entity
@Table(name = "orc", catalog = "DIAGE", schema = "atb")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Orc.findAll", query = "SELECT o FROM Orc o"),
    @NamedQuery(name = "Orc.findById", query = "SELECT o FROM Orc o WHERE o.id = :id"),
    @NamedQuery(name = "Orc.findByNomeItem", query = "SELECT o FROM Orc o WHERE o.nomeItem = :nomeItem"),
    @NamedQuery(name = "Orc.findByDescItem", query = "SELECT o FROM Orc o WHERE o.descItem = :descItem"),
    @NamedQuery(name = "Orc.findByValor", query = "SELECT o FROM Orc o WHERE o.valor = :valor"),
    @NamedQuery(name = "Orc.findByDtRef", query = "SELECT o FROM Orc o WHERE o.dtRef = :dtRef")})
public class Orc implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @NotNull
    @Column(name = "id")
    private Integer id;
    @Size(max = 100)
    @Column(name = "NomeItem")
    private String nomeItem;
    @Size(max = 255)
    @Column(name = "DescItem")
    private String descItem;
    // @Max(value=?)  @Min(value=?)//to enforce field validation to known decimal range values
    @Column(name = "valor")
    private Double valor;
    @Column(name = "DtRef")
    @Temporal(TemporalType.TIMESTAMP)
    private Date dtRef;
    @OneToMany(mappedBy = "idOrc")
    private Collection<HrCapacit30h> hrCapacit30hCollection;

    //getters/setters/equals/hashCode ommited    

}

The EJB (an abstract facade): EJB(抽象外观):

//imports ommited

public abstract class AbstractFacade<T> {
    private Class<T> entityClass;

    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    protected abstract EntityManager getEntityManager();

    public void create(T entity) {
        getEntityManager().persist(entity);
    }

    public void edit(T entity) {
        getEntityManager().merge(entity);
    }

    public void remove(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    public T find(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<T> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        q.setMaxResults(range[1] - range[0] + 1);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
        cq.select(getEntityManager().getCriteriaBuilder().count(rt));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }

}

The hr_capacit30h EJB facade: hr_capacit30h EJB外观:

//imports ommited

@Stateless
public class HrCapacit30hFacade extends AbstractFacade<HrCapacit30h> {
    @PersistenceContext(unitName = "atb-hrCapacit30PU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public HrCapacit30hFacade() {
        super(HrCapacit30h.class);
    }

}

The Orc EJB facade: Orc EJB外观:

//imports ommited

@Stateless
public class OrcFacade extends AbstractFacade<Orc> {
    @PersistenceContext(unitName = "atb-hrCapacit30PU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public OrcFacade() {
        super(Orc.class);
    }

}

Thanks in advance. 提前致谢。

After a long way studying it: 经过长时间的研究:

/**
 *
 * @author jMarcel
 */
@ManagedBean
@RequestScoped
public class ChartBean {

public ChartBean() {
}

private final Map<Integer, Map<String, Number>> HorasRealizadasPorFunci = new HashMap<>();
private final Map<Integer, Map<String, Number>> HorasOrcadasPorFunci = new HashMap<>();
private CartesianChartModel cartesianChartModel;

@EJB
private OrcFacade of;

@PostConstruct
private void initialize() {
    cartesianChartModel = new CartesianChartModel();
    createCartesianChartModel();
}

private void createCartesianChartModel() {
    List<Orc> orcado = of.findAll();
    List<Integer> orcadoList = new ArrayList<>();
    List<Integer> realizadoList = new ArrayList<>();

    //rlz Series
    for (Orc o : orcado) {
        int horasRlz = 0;
        for (HrCapacit30h r : o.getHrCapacit30hCollection()) {
            horasRlz = r.getRealizado();
            addOrUpdateRlz(r.getHrCapacit30hPK().getMatricula(), r.getNome(), horasRlz);
            realizadoList.add(r.getHrCapacit30hPK().getMatricula());
        }
    }

    //orc Series
    for (Orc o : orcado) {
        int horasOrc = 0;
        for (HrCapacit30h r : o.getHrCapacit30hCollection()) {
            horasOrc = r.getIdOrc().getValor().intValue();
            addOrUpdateOrc(r.getHrCapacit30hPK().getMatricula(), r.getNome(), horasOrc);
            orcadoList.add(r.getHrCapacit30hPK().getMatricula());
        }
    }

    Map<Object, Number> orcMap = new HashMap<>();
    Map<Object, Number> rlzMap = new HashMap<>();

    for (Integer i : realizadoList) {
        populateMap(rlzMap, HorasRealizadasPorFunci.get(i));
    }

    for (Integer i : orcadoList) {
        populateMap(orcMap, HorasOrcadasPorFunci.get(i));
    }

    ChartSeries orcadoSeries = new ChartSeries("Orçado");
    orcadoSeries.setData(orcMap);
    ChartSeries realizadoSeries = new ChartSeries("Realizado");
    realizadoSeries.setData(rlzMap);
    cartesianChartModel.addSeries(orcadoSeries);
    cartesianChartModel.addSeries(realizadoSeries);

}

private void addOrUpdateRlz(Integer matricula, String funci, Number horas) {
    Map<String, Number> map = HorasRealizadasPorFunci.get(matricula);
    if (map == null) {
        map = new HashMap<>();
        HorasRealizadasPorFunci.put(matricula, map);
    }
    Number n = map.get(funci);
    if (n == null) {
        map.put(funci.toUpperCase(), horas);
    } else {
        map.put(funci.toUpperCase(), horas.intValue());
    }
}

private void addOrUpdateOrc(Integer matricula, String funci, Number horas) {
    Map<String, Number> map = HorasOrcadasPorFunci.get(matricula);
    if (map == null) {
        map = new HashMap<>();
        HorasOrcadasPorFunci.put(matricula, map);
    }
    Number n = map.get(funci);
    if (n == null) {
        map.put(funci.toUpperCase(), horas);
    } else {
        map.put(funci.toUpperCase(), horas.intValue());
    }
}

private void populateMap(Map<Object, Number> map, Map<String, Number> data) {
    if (data == null) {
        return;
    }
    for (String key : data.keySet()) {
        Number n = map.get((Object) key);
        if (n == null) {
            map.put((Object) key, data.get(key));
        } else {
            map.put((Object) key, n.intValue() + data.get(key).intValue());
        }
    }
}

public CartesianChartModel getCartesianChartModel() {
    return cartesianChartModel;
}

public void setCartesianChartModel(CartesianChartModel cartesianChartModel) {
    this.cartesianChartModel = cartesianChartModel;
}
}

You need to create a ChartSeries (for category chart) or LineChartSeries (for linear chart) object, fill it with your values, and finally add the object to the Cartesian Model. 您需要创建一个ChartSeries(用于类别图)或LineChartSeries(用于线性图)对象,并用您的值填充它,最后将对象添加到笛卡尔模型中。 That's all. 就这样。

Have a look at the official example 看看官方的例子

private void createCategoryModel() {  // category chart
            categoryModel = new CartesianChartModel();  

            ChartSeries boys = new ChartSeries();  
            boys.setLabel("Boys");  

            boys.set("2004", 120);  
            boys.set("2005", 100);  
            boys.set("2006", 44);  
            boys.set("2007", 150);  
            boys.set("2008", 25);  

            ChartSeries girls = new ChartSeries();  
            girls.setLabel("Girls");  

            girls.set("2004", 52);  
            girls.set("2005", 60);  
            girls.set("2006", 110);  
            girls.set("2007", 135);  
            girls.set("2008", 120);  

            categoryModel.addSeries(boys);  
            categoryModel.addSeries(girls);  
        } 

private void createLinearModel() {  //linear chart
                linearModel = new CartesianChartModel();  

                LineChartSeries series1 = new LineChartSeries();  
                series1.setLabel("Series 1");  

                series1.set(1, 2);  
                series1.set(2, 1);  
                series1.set(3, 3);  
                series1.set(4, 6);  
                series1.set(5, 8);  

                LineChartSeries series2 = new LineChartSeries();  
                series2.setLabel("Series 2");  
                series2.setMarkerStyle("diamond");  

                series2.set(1, 6);  
                series2.set(2, 3);  
                series2.set(3, 2);  
                series2.set(4, 7);  
                series2.set(5, 9);  

                linearModel.addSeries(series1);  
                linearModel.addSeries(series2);  
     } 

Edit : 编辑:

Create and initialize two ChartSeries objects. 创建并初始化两个ChartSeries对象。 Then fill them while iterating through the list. 然后在遍历列表的同时填充它们。 Something like this should work : 这样的事情应该工作:

ChartSeries a = new ChartSeries();
ChartSeries b = new ChartSeries();
HrCapacit30h tmp = null;

for(int i =0; i<hrCapacit30h.size();i++){
tmp=hrCapacit30h.get(i);
a.set(tmp.getRealizado(), tmp.getNome());
b.set(tmp.getOcr().getValor(), tmp.getNome());
}

cartesianChartModel.addSeries(a);
cartesianChartModel.addSeries(b);

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM