1

我已经有一个 CRUD webApp (JSF+EJB+JPA),我正在尝试开发一个 chartBean 类,以便可以在 View 层中使用它。要渲染的数据(通过 Primefaces-4 BarChart)应该从数据库中读取。

在图表中,我有 2 个要显示的 chartSeries:

  • chartSeries1:employeeGoal -> 下面的 Orc 实体类中映射的 'valor' 浮点列;
  • chartSeries2:employeeAccomplished -> 在下面的 hr_capacit30h 实体类中映射的 'Realizado' 整数列。

X 轴应显示小时数(基于上面的“chartSeries2”值)。

Y 轴应显示employeeName(下面的hr_capacit30h 实体类中的'nome' 字符串字段)。

有谁知道如何开发下面的 createCartesianChartModel() 方法以在 jsf 页面中使用?

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
    }
}

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    
}

Entity 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    

}

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();
    }

}

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);
    }

}

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);
    }

}

提前致谢。

4

2 回答 2

2

经过长时间的研究:

/**
 *
 * @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;
}
}
于 2013-11-26T20:28:12.300 回答
1

您需要创建一个 ChartSeries(用于类别图)或 LineChartSeries(用于线性图)对象,用您的值填充它,最后将该对象添加到笛卡尔模型中。就这样。

看看官方的例子

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);  
     } 

编辑 :

创建并初始化两个 ChartSeries 对象。然后在遍历列表时填充它们。像这样的东西应该工作:

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);

希望能帮助到你。

于 2013-10-29T21:34:26.627 回答