I am about developing a small application using EJB JPA MySQL netbeans7.2,
so my application has the following goal: get the list of names and their IDs and add other names to the list.
My classes are:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.rachid.entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "employee")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e"),
#NamedQuery(name = "Employee.findById", query = "SELECT e FROM Employee e WHERE
e.id = :id"),
#NamedQuery(name = "Employee.findByName", query = "SELECT e FROM Employee e WHERE
e.name = :name")})
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Size(max = 20)
#Column(name = "name")
private String name;
public Employee() {
}
public Employee(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Employee)) {
return false;
}
Employee other = (Employee) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.rachid.entities.Employee[ id=" + id + " ]";
}
}
The session bean that uses the entity is:
package com.rachid.session;
import com.rachid.entities.Employee;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
#Stateless
#LocalBean
public class EmployeeSessionBean {
#PersistenceContext(unitName = "EnterpriseApplication1-ejbPU")
private EntityManager em;
public List<Employee> getAllEmployees() {
Query query = em.createNamedQuery("Employee.findAll");
return query.getResultList();
}
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
public Employee updateEmployee(Employee parameter) {
return em.merge(parameter);
}
public void addEmployee(Employee employee){
em.persist(employee);
}
}
The managed bean is:
package managedBeans;
import com.rachid.entities.Employee;
import com.rachid.session.EmployeeSessionBean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ViewScoped;
import javax.inject.Named;
#Named(value = "employeeManagedBean")
#ViewScoped
public class EmployeeManagedBean implements Serializable {
public EmployeeManagedBean() {
}
#EJB
private EmployeeSessionBean employeeBean;
private Employee employee;
private Employee newEmployee;
private List<Employee> employees;
public List<Employee> getEmployees(){
employees = new ArrayList<Employee>();
return employeeBean.getAllEmployees();
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public void add(){
if(newEmployee!= null){
employeeBean.addEmployee(newEmployee);
}
}
public String update(){
System.out.println("***UPDATE***");
employee = employeeBean.updateEmployee(employee);
return "Employees List";
}
public Employee getNewEmployee() {
return newEmployee;
}
public void setNewEmployee(Employee newEmployee) {
this.newEmployee = newEmployee;
}
}
Unfortunately, when I invoke the method addEmployee in the jsf page, nothing is written to the database. I was worried about the transaction management handled by the container; that is the updates and inserts are managed by the container and it may not be written to the database immediately, so I annotate the addEmployee method (in the EJB) with the #TransationalAttribute(TransactionalAttributeType.REQUIRED) but the result still the same.
Is there anything that I am missing here in my code or my understanding of the issue's context?
(Note that I am a beginner in EJB :) )
Here are the jsf pages (an index page that shows the list and another one to add new element to the list):
index.xhtml file:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
Hello from Facelets
<f:view>
<h:form>
<h1><h:outputText value="List"/></h1>
<h:dataTable value="#{employeeManagedBean.employees}" var="item">
<h:column>
<f:facet name="header">
<h:outputText value="Id"/>
</f:facet>
<h:outputText value="#{item.id}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Name"/>
</f:facet>
<h:outputText value="#{item.name}"/>
</h:column>
</h:dataTable>
</h:form>
</f:view>
<h:form>
<h:commandButton value="nouveau" action="ajouter.xhtml" type="submit" />
</h:form>
</h:body>
ajouter.xhtml file:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org
/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:body>
<f:view>
<h:form>
<h1><h:outputText value="Create/Edit"/></h1>
<h:panelGrid columns="2">
<h:outputLabel value="Id:" for="id" />
<h:inputText id="id" value="#{employeeManagedBean.newEmployee.id}"
title="Id"
required="true" requiredMessage="The Id field is required."/>
<h:outputLabel value="Name:" for="name" />
<h:inputText id="name" value="#{employeeManagedBean.newEmployee.name}"
title="Name" />
</h:panelGrid>
</h:form>
</f:view>
<h:form>
<h:commandButton value="ajouter" action="index.xhtml" type="submit"
actionListener="#{employeeManagedBean.add()}" />
</h:form>
</h:body>
Related
I'm using a normal datatable with lazyloading and rowexpansion with a nested table and I have problems by opening the rowexpansion after lazyloading. ScrollRows is setted to 150.
<ui:composition template="/ressources/basic.xhtml" xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui">
<ui:define name="title">#{label['template.tab1']}</ui:define>
<ui:define name="content">
<h:form id="crateTbl">
<p:dataTable rowExpandMode="single" id="cTbl" var="crate" value="#{cratesView.lazyModel}" selectionMode="single"
filteredValue="#{cratesView.filteredCrates}" selection="#{cratesView.selectedCrate}"
lazy="true" liveScroll="true" scrollRows="150"
widgetVar="cratesTbl" rowKey="#{crate.id}" scrollable="true" scrollHeight="550">
<p:column style="width:16px" exportable="false">
<p:rowToggler />
</p:column>
<p:column headerText="#{label['crate.col.grp']}" filterStyle="width:60px;" filterBy="#{crate.grp}" filterMatchMode="contains" width="60">
<h:outputText value="#{crate.grp}"/>
</p:column>
...additional columns of crate.
<p:rowExpansion >
<p:panelGrid columnClasses="label,value" >
<div class="remark-label"><b>#{label['crateview.toggle.remark']}</b>: <h:outputLabel value="#{crate.remark}"/></div>
<p:dataTable id='bTbl' var="bottle" value="#{cratesView.getBottles2Crate(crate)}"
widgetVar="bottleTbl" rowKey="#{bottle.id}" scrollable="true" scrollHeight="300">
<p:column headerText="#{label['bottle.col.grp']}" width="50">
<h:outputText value="#{bottle.grp}"/>
</p:column>
...additional columns of bottle
</p:dataTable>
</p:column>
</p:row>
</p:panelGrid>
</p:rowExpansion>
</p:dataTable>
</h:form>
</ui:define>
and Bean:
#ManagedBean(name = "cratesView")
#ViewScoped
public class CrateView implements Serializable {
//object definitions
#PostConstruct
public void init() {
//init some objects
lazyModel = new LazyCrateDatamodel(cratesList);
}
public LazyDataModel<Crate> getLazyModel() {
return lazyModel;
}
public void setLazyModel(LazyCrateDatamodel lazyModel){
this.lazyModel = lazyModel;
}
public void setSelectedCrate(final Crate c){
this.selectedCrate = c;
}
public Crate getSelectedCrate() {
return this.selectedCrate;
}
public List<Crate> getFilteredCrates() {
return filteredCrates;
}
public void setFilteredCrates(List<Crate> filteredCrates) {
this.filteredCrates = filteredCrates;
}
public List<Bottle> getBottles2Crate(final Crate c)
{
int grp = c.getGrp(); //
return gProvider.getBottlesByCrate(calculated.getGrp(), 0);
}
}
Everything runs fine on the firstpage, opening the expansion shows correct data in the table. After loading the next 150 rows and scrolling back to e.g. the first row and opening the expansion the data of a wrong crate is loaded. cratesView.getBottles2Crate(crate) is called with a crate-object shifted by n*150(n - numbers of loadings). The object of the rowtoggling-event is not the same of the datamodel. On the other side setSelectedCrate gets the right object.
Do I have something misconfigurated or is there a hint in the docs using rowexpansion and lazyloading...
Thanks for some hints.
Edit: Correct some syntax.
Sorry for the missing information:
Mojarra JSF Implementation 2.3.0 (20170310-1214)
Primeface 6.2
I tested it parallel with a minimal version:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Lazy Test</title>
<link rel="icon" href="imgs/favicon.ico" type="image/x-icon" />
</h:head>
<body>
<h:form id="crateTbl">
<p:dataTable rowExpandMode="single" id="cTbl" var="crate" value="#{lazyView.model}" selectionMode="single" selection="#{lazyView.selectedCrate}"
lazy="true" liveScroll="true" scrollRows="150"
widgetVar="cratesTbl" rowKey="#{crate.id}" scrollable="true" scrollHeight="550">
<p:column style="width:16px" exportable="false">
<p:rowToggler />
</p:column>
<p:column headerText="Kistengrp" width="60">
<h:outputText value="#{crate.grp}"/>
</p:column>
<p:column headerText="Kistennamen" width="250">
<h:outputText value="#{crate.name}"/>
</p:column>
<p:column headerText="Flaschengrp" width="100">
<h:outputText value="#{crate.bgrp}"/>
</p:column>
<p:rowExpansion >
<p:panelGrid columnClasses="label,value" >
<p:dataTable id='bTbl' var="bottle" value="#{lazyView.getBottlesByCrate(crate)}" widgetVar="bottleTbl" rowKey="#{bottle.id}" scrollable="true" scrollHeight="300">
<p:column headerText="Gruppe" width="50">
<h:outputText value="#{bottle.grp}"/>
</p:column>
<p:column headerText="Name" width="250">
<h:outputText value="#{bottle.name}"/>
</p:column>
<p:column headerText="Id" width="100">
<h:outputText value="#{bottle.id}"/>
</p:column>
</p:dataTable>
</p:panelGrid>
</p:rowExpansion>
</p:dataTable>
</h:form>
</body>
</html>
Classes:
Testdata provider:
package de.test;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
#ManagedBean(name = "testservice")
#ApplicationScoped
public class AssortmentProvider {
private final static String[] NAMES = {"Uerige","Koelsch","Wasser","Saft","Limo","Cola","Kupfer","Messing"};
private final static int[] BGRPS = {1,12,15,20,24,25,26,30,100,112,155,200,201,242,250};
private final static int[] CGRPS = {1000,1020,1050,2000,2400,2500,2600,3000,1006,1120,1550,2050,2010,2420,2500};
private List<Crate> crates;
private List<Bottle> bottles;
#PostConstruct
public void init() {
this.createBottles();
this.createCrates();
}
public List<Crate> getCrates() { return crates; }
public List<Bottle> getBottles() { return bottles; }
public List createCrates() {
crates = new ArrayList<>();
for(int i=0;i<500;i++) {
int n = (int) (Math.random() * 8);
int g = (int) (Math.random() * 15);
int b = (int) (Math.random() * 15);
Crate c = new Crate(NAMES[n], i, CGRPS[g]);
c.setBgrp(BGRPS[b]);
crates.add(c);
}
return crates;
}
public List createBottles() {
bottles = new ArrayList<>();
for(int i=0;i<500;i++) {
int n = (int) (Math.random() * 8);
int b = (int) (Math.random() * 15);
Bottle btl = new Bottle("B_" + NAMES[n], i, BGRPS[b]);
bottles.add(btl);
}
return bottles;
}
}
Entities Crate:
package de.test;
public class Crate extends Entity {
private int bgrp;
public Crate(String name, int id, int cgrp) { super(name,id,cgrp); }
public int getBgrp() { return bgrp; }
public void setBgrp(int bgrp) { this.bgrp = bgrp; }
#Override
public String toString() { return "Crate{" + "name=" + name + ", id=" + id + ", grp=" + grp + ", bgrp=" + bgrp +'}'; }
}
next Bottle:
package de.test;
public class Bottle extends Entity {
public Bottle(String name, int id, int grp) { super(name,id,grp); }
#Override
public String toString() { return "Bottle{" + "name=" + name + ", id=" + id + ", grp=" + grp + '}'; }
}
next Entity:
package de.test;
public class Entity {
protected String name;
protected int id;
protected int grp;
public Entity(String name, int id, int grp) {
this.name = name;
this.id = id;
this.grp = grp;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public int getGrp() { return grp; }
public void setGrp(int grp) { this.grp = grp; }
}
next LazyView:
package de.test;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
#ManagedBean(name = "lazyView")
#ViewScoped
public class LazyView implements Serializable {
#ManagedProperty("#{testservice}")
AssortmentProvider service;
List<Crate> crateList;
Crate selectedCrate;
LazyCrateModel model;
#PostConstruct
public void init() {
crateList = this.service.createCrates();
model = new LazyCrateModel(crateList);
}
public void setService(AssortmentProvider service) { this.service = service; }
public Crate getSelectedCrate() { return selectedCrate; }
public void setSelectedCrate(Crate selectedCrate) { this.selectedCrate = selectedCrate; }
public List<Crate> getCrateList() { return crateList; }
public void setCrateList(List<Crate> crateList) { this.crateList = crateList; }
public LazyCrateModel getModel() { return model; }
public List<Bottle> getBottlesByCrate(final Crate c) {
System.out.println(c);
List<Bottle> l = new ArrayList<>();
for(Bottle b : service.getBottles())
{
if( b.getGrp() == c.getBgrp())
l.add(b);
}
return l;
}
}
next LazyDatamodel:
package de.test;
import java.util.List;
import java.util.Map;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
public class LazyCrateModel extends LazyDataModel<Crate> {
private final List<Crate> list;
public LazyCrateModel(List<Crate> list) { this.list = list; }
#Override
public Integer getRowKey(Crate object) { return object.getId(); }
#Override
public List<Crate> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
this.setRowCount(list.size());
if(first + pageSize > list.size()) {
pageSize = list.size() - first;
}
List<Crate> sub = list.subList(first, first + pageSize);
return sub;
}
#Override
public Crate getRowData(String str) {
int idx = Integer.parseInt(str);
for(Crate c : list) {
if(c.getId() == idx)
return c;
}
return null;
}
}
It's the same behavior: After one loading scrolling to the beginning, the given crate is the 150 shifted crate, not crate[0].
Hope someone can verify this behavior.
i m new in primefaces can you help me plase i want to fill a dataTable primefaces by data from mysql database table name is products
i got the bean Product as below :
package ma.supmti.jsf.model;
import java.util.Date;
public class Product {
private Integer id;
private String name;
private Integer prixAchat;
private Integer prixVente;
private Date dateCreation;
public Product() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPrixAchat() {
return prixAchat;
}
public void setPrixAchat(Integer prixAchat) {
this.prixAchat = prixAchat;
}
public Integer getPrixVente() {
return prixVente;
}
public void setPrixVente(Integer prixVente) {
this.prixVente = prixVente;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
}
the managedBean ServiceProduct as a service
package ma.supmti.jsf.service;
import java.util.List;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import ma.supmti.jsf.dao.DAOProduct;
import ma.supmti.jsf.dao.IDAOProduct;
import ma.supmti.jsf.model.Product;
#ManagedBean(name = "serviceProduct")
#ApplicationScoped
public class ServiceProduct implements IServiceProduct {
IDAOProduct dao = new DAOProduct();
public ServiceProduct() {
}
public void addProduct() {
dao.addProduct();
}
public List<Product> selectProduct() {
return dao.selectProduct();
}
}
the Product ManagedBean :
package ma.supmti.jsf.presentation;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import ma.supmti.jsf.model.Product;
import ma.supmti.jsf.service.ServiceProduct;
#ManagedBean(name="productM")
#ApplicationScoped
public class ProductMB implements Serializable {
private static final long serialVersionUID = 1L;
private List<Product> produits;
#ManagedProperty("#{serviceProduct}")
private ServiceProduct srvProduct;
#PostConstruct
public void init() {
setProduits(srvProduct.selectProduct());
}
public void setSrvProduct(ServiceProduct srvProduct) {
this.srvProduct = srvProduct;
}
public List<Product> getProduits() {
return produits;
}
public void setProduits(List<Product> produits) {
this.produits = produits;
}
}
and the hibernate dao to load data from mysql database
package ma.supmti.jsf.dao;
import org.hibernate.query.Query;
import ma.supmti.jsf.model.Product;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class DAOProduct implements IDAOProduct {
public DAOProduct() {
}
public void addProduct() {
}
public List<Product> selectProduct() {
Configuration config = new Configuration();
config=config.configure("hibernate.cfg.xml");
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
Query query = session.createQuery("from Product");
List<Product> produits = query.list();
for(Product produit:produits) {
System.out.println("prix "+produit.getPrixAchat());
System.out.println("Prenom "+produit.getPrixVente());
}
return produits;
}
}
here is the dataTable i want to display
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xlmns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title>LISTE DES PRODUITS </title>
<style type="text/css">
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 14px;
}
.header {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 18px;
}
.bottom {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 9px;
text-align: center;
vertical-align: middle;
color: #8E969D;
}
</style>
</h:head>
<body bgcolor="#ffffff">
<p:dataTable value="#{ProductM.produits}" var="produit" id="produit" lazy="true" paginator="true" rows="10">
<f:facet name="header">
Liste des produits .....................
</f:facet>
<p:column headerText="Id">
<h:outputText value="#{produit.id}" />
</p:column>
<p:column headerText="Name">
<h:outputText value="#{produit.name}" />
</p:column>
<p:column headerText="Prix Achats">
<h:outputText value="#{produit.prixachat}" />
</p:column>
<p:column headerText="Prix Vente">
<h:outputText value="#{produit.prixvente}" />
</p:column>
<p:column headerText="Date Creation">
<h:outputText value="#{produit.datecreation}" />
</p:column>
</p:dataTable>
</body>
</html>
thank you for your help
I have a datatable from database and I would like details of one of the rows appear in a new table when I click on the "OPEN" button as in the screenshot below.
When I click on the OPEN button I get "No records found " as in the next screenshot below
Here is part of the index.xhtml
//
APP WEB
<p:ajax event="rowEdit" listener="#{transaction.onRowEdit}" update=":form1:messages" />
<p:ajax event="rowEditCancel" listener="#{transaction.onRowCancel}" update=":form1:messages" />
<p:column headerText="Reference">
<p:commandLink value="#{c.reference}" action="/faces/global/SingleTx.xhtml" target="_blank" >
<f:setPropertyActionListener target="#{transaction.showSelectedTx(reference)}" value="#{c}" />
</p:commandLink>
</p:column>
<p:column headerText="Rartner">
#{c.pname}
</p:column>
<p:column headerText="Status">
#{c.fk_status}
</p:column>
<p:column headerText="Sender">
#{c.sendername}
</p:column>
<p:column headerText="Beneficiary">
#{c.beneficiaryname}
</p:column>
<p:column headerText="Amounts">
#{c.beneficiary_currency} #{c.beneficiary_amount}
</p:column>
<p:column headerText="Action">
<p:commandButton style="float:right" value="Print" >
<p:confirm header="#{cd.reference}" message="Are you sure?" icon="ui-icon-alert" />
<p:button value="Open" href="/faces/global/SingleTx.xhtml" target="_self" />
</p:commandButton>
</p:column>
<p:column style="width:32px">
<p:rowEditor />
</p:column>
</p:dataTable>
<p:dialog modal="true" width="800px" height="400px" widgetVar="singletx"
id="dialog">
Name :#{transaction.showSelectedTx(reference)}
</p:dialog>
</h:form>
Here is the backing bean:
package com.mycompany.data;
/**
*
* #author bryan
*/
import conn.DBConnector;
import java.io.Serializable;
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 javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean(name = "transaction")
#SessionScoped
public class TransactionBean implements Serializable {
//added
private static final long serialVersionUID = 1L;
public String reference;
public String fk_status;
public String sendername;
public String beneficiaryname;
public String beneficiary_currency;
public double beneficiary_amount;
public String pname;
Transaction user;
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getFk_status() {
return fk_status;
}
public void setFk_status(String fk_status) {
this.fk_status = fk_status;
}
public String getSendername() {
return sendername;
}
public void setSendername(String sendername) {
this.sendername = sendername;
}
public String getBeneficiaryname() {
return beneficiaryname;
}
public void setBeneficiaryname(String beneficiaryname) {
this.beneficiaryname = beneficiaryname;
}
public String getBeneficiary_currency() {
return beneficiary_currency;
}
public void setBeneficiary_currency(String beneficiary_currency) {
this.beneficiary_currency = beneficiary_currency;
}
public double getBeneficiary_amount() {
return beneficiary_amount;
}
public void setBeneficiary_amount(double beneficiary_amount) {
this.beneficiary_amount = beneficiary_amount;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
//resource injection
#Resource(name = "jdbc/primefaces")
//connect to DB and get customer list
public List<Transaction> getTransactionList() throws SQLException, ClassNotFoundException {
Connection con = null;
con = DBConnector.getDBConnection();
if (con == null) {
throw new SQLException("Can't get database connection");
}
PreparedStatement ps
= con.prepareStatement(
"select tx.reference,p.pname,ts.name, tx.sendername, tx.beneficiaryname, tx.beneficiary_currency,tx.beneficiary_amount from transaction_stage tx join transaction_status ts on tx.fk_status=ts.id join partner p on tx.fk_partner=p.id");
//get customer data from database
ResultSet result = ps.executeQuery();
List<Transaction> list = new ArrayList<Transaction>();
while (result.next()) {
Transaction cust = new Transaction();
cust.setReference(result.getString("reference"));
cust.setFk_status(result.getString("name"));
cust.setSendername(result.getString("sendername"));
cust.setBeneficiaryname(result.getString("beneficiaryname"));
cust.setBeneficiary_currency(result.getString("beneficiary_currency"));
cust.setBeneficiary_amount(result.getDouble("beneficiary_amount"));
cust.setPname(result.getString("pname"));
//store all data into a List
list.add(cust);
}
return list;
//added
}
//view single transaction
private List<Transaction> selectSingleTx;
public Transaction getUser() {
return user;
}
public void setUser(Transaction user) {
this.user = user;
}
public List<Transaction> getSelectSingleTx() {
return selectSingleTx;
}
public void setSelectSingleTx(List<Transaction> selectSingleTx) {
this.selectSingleTx = selectSingleTx;
}
public void showSelectedTx(String reference){
Connection con=DBConnector.getDBConnection();
if(con==null){
System.out.println("No db connection");
}
String ref=getReference();
try {
String q="select tx.reference,p.pname,ts.name, tx.sendername, tx.beneficiaryname, tx.beneficiary_currency,tx.beneficiary_amount from transaction_stage tx join transaction_status ts on tx.fk_status=ts.id join partner p on tx.fk_partner=p.id where tx.reference="+ref+"";
PreparedStatement ps=null;
ResultSet rs=null;
ps.setString(1, reference);
rs=ps.executeQuery();
display(rs);
} catch (Exception e) {
}
}
public void selectTx(String reference){
showSelectedTx(reference);
}
// to be implemented later
private static void display(ResultSet myRs) throws SQLException {
while (myRs.next()) {
String sendername = myRs.getString("sendername");
String beneficiaryname = myRs.getString("beneficiaryname");
//double salary = myRs.getDouble("salary");
String department = myRs.getString("department");
System.out.printf("%s, %s \n", sendername, beneficiaryname);
}
}
}
//
As per the Reference link, you need to include the value of c.reference in the link
value="#{c.reference}"
See JSF ViewParam from CommandButton
or
How to pass a parameter along with h:commandButton
As stated in the question I am having trouble adding to database without entering an ID, I have my ID set to auto increment so I would imagine it should of added the records and incremented the ID, it works fine when i un-comment out the id input field and enter an ID manually in the form. I will post my code and the errors. Let me know if I need to supply any more information
Thanks
add.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<f:view>
<h:form>
<h1><h:outputText value="Create/Edit"/></h1>
<h:panelGrid columns="2">
<h:outputLabel value="Artist:" for="artist" />
<h:inputText id="artist" value="#{cdController.c.artist}" title="Artist" />
<h:outputLabel value="Duration:" for="duration" />
<h:inputText id="duration" value="#{cdController.c.duration}" title="Duration" />
<h:outputLabel value="Title:" for="title" />
<h:inputText id="title" value="#{cdController.c.title}" title="Title" />
<!-- <h:outputLabel value="Id:" for="id" />
<h:inputText id="id" value="#{cdController.c.id}" title="Id" required="true" requiredMessage="The Id field is required."/>-->
<h:commandButton value="Save" action="#{cdController.add()}"></h:commandButton>
</h:panelGrid>
</h:form>
</f:view>
</h:body>
</html>
index.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title> Title</title>
</h:head>
<h:body>
<h:form>
<h:link value="add CD" outcome="add"></h:link>
<h:dataTable var="c" value="#{cdController.findAll()}" border="1" cellpadding="2">
<h:column>
<f:facet name="header">ID</f:facet>
<h:outputText value="#{c.id}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">Artist</f:facet>
<h:outputText value="#{c.artist}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">Duration</f:facet>
<h:outputText value="#{c.duration}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">Title</f:facet>
<h:outputText value="#{c.title}"></h:outputText>
</h:column>
</h:dataTable>
</h:form> </h:body>
</html>
CdFacade
package model;
import entities.Cd;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless
public class CdFacade extends AbstractFacade<Cd> {
#PersistenceContext(unitName = "CD-Store-ejbPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public CdFacade() {
super(Cd.class);
}
}
CdController
package controller;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.util.AbstractCollection.*;
import javax.ejb.EJB;
import model.CdFacade;
import entities.*;
import java.util.*;
#Named(value = "cdController")
#SessionScoped
public class CdController implements Serializable {
#EJB
private CdFacade cdFacade;
private Cd c = new Cd();
public Cd getC() {
return c;
}
public void setC(Cd c) {
this.c = c;
}
public String add()
{
this.cdFacade.create(this.c);
return "index";
}
public CdController() {
}
public List<Cd> findAll()
{
return this.cdFacade.findAll();
}
}
Abstract Facade
package model;
import java.util.List;
import javax.persistence.EntityManager;
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();
}
}
Cd.java
package entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "CD")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Cd.findAll", query = "SELECT c FROM Cd c"),
#NamedQuery(name = "Cd.findByArtist", query = "SELECT c FROM Cd c WHERE c.artist = :artist"),
#NamedQuery(name = "Cd.findByDuration", query = "SELECT c FROM Cd c WHERE c.duration = :duration"),
#NamedQuery(name = "Cd.findByTitle", query = "SELECT c FROM Cd c WHERE c.title = :title"),
#NamedQuery(name = "Cd.findById", query = "SELECT c FROM Cd c WHERE c.id = :id")})
public class Cd implements Serializable {
private static final long serialVersionUID = 1L;
#Size(max = 255)
#Column(name = "ARTIST")
private String artist;
#Size(max = 255)
#Column(name = "DURATION")
private String duration;
#Size(max = 255)
#Column(name = "TITLE")
private String title;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "ID")
private Long id;
public Cd() {
}
public Cd(Long id) {
this.id = id;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Cd)) {
return false;
}
Cd other = (Cd) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.Cd[ id=" + id + " ]";
}
}
Stack Trace
javax.faces.el.EvaluationException: javax.ejb.EJBException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.ejb.EJBException
at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:752)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:702)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:507)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4566)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2074)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2044)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:220)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy432.create(Unknown Source)
at model.__EJB31_Generated__CdFacade__Intf____Bean__.create(Unknown Source)
at controller.CdController.add(CdController.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at javax.el.ELUtil.invokeMethod(ELUtil.java:332)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:537)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
at com.sun.el.parser.AstValue.invoke(AstValue.java:283)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 36 more
Caused by: javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'. Please refer to embedded ConstraintViolations for details.
at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.validateOnCallbackEvent(BeanValidationListener.java:108)
at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.prePersist(BeanValidationListener.java:77)
at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyListener(DescriptorEventManager.java:748)
at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyEJB30Listeners(DescriptorEventManager.java:691)
at org.eclipse.persistence.descriptors.DescriptorEventManager.executeEvent(DescriptorEventManager.java:229)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectClone(UnitOfWorkImpl.java:4314)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:4291)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:521)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4233)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:507)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:287)
at model.AbstractFacade.create(AbstractFacade.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:64)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
at sun.reflect.GeneratedMethodAccessor1113.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.GeneratedMethodAccessor1128.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
... 53 more
I am facing an issue while tryin to group data with primefaces subtale component. My columns are grouped but the first result still the same row as shown in the screen shot below :
Normaly I should have other apart from AIR. But this is the result I have got.
Can some one help me understand what happening. I have followed the PrimeFaces show case and develop classes to produce this subtable:
This is the managed bean:
package tg.moov.imereport.mbean;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Named;
import tg.moov.imereport.service.DownStream;
import tg.moov.imereport.service.DownStreamTotal;
#Named
#Stateless
public class GroupedDataMBean {
#EJB private DownStreamMBean ds;
#EJB private DownStreamTotalMBean dst;
private Period period = new Period();
private List<GroupedDownStream> downStreams;
/**
* #return the period
*/
public Period getPeriod() {
return period;
}
/**
* #param period the period to set
*/
public void setPeriod(Period period) {
this.period = period;
}
public GroupedDataMBean() {
}
/**
*
*/
public void populateDownStreams() {
downStreams = new ArrayList<GroupedDownStream>();
for (DownStream d : ds.getDownStreamsService()) {
GroupedDownStream gds = new GroupedDownStream();
gds.setDownStream(d.getIDDownStream());
dst.setPeriod(period);
for(DownStreamTotal dt : dst.displayGroupedDataByDownStream(d)) {
gds.getDownStreamsDetails().add(dt);
}
downStreams.add(gds);
}
}
/**
*
* #return a List of GroupedDownStream
*/
public List<GroupedDownStream> getGroupedDownStreams() {
return downStreams;
}
}
this is the Master class :
package tg.moov.imereport.mbean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import tg.moov.imereport.service.DownStreamTotal;
public class GroupedDownStream implements Serializable {
private String downStream;
private List<DownStreamTotal> downStreamsDetails;
/**
* #return the downStream
*/
public String getDownStream() {
return downStream;
}
/**
* #param downStream the downStream to set
*/
public void setDownStream(String downStream) {
this.downStream = downStream;
}
/**
* #return the downStreamsDetails
*/
public List<DownStreamTotal> getDownStreamsDetails() {
return downStreamsDetails;
}
/**
* #param downStreamsDetails the downStreamsDetails to set
*/
public void setDownStreamsDetails(List<DownStreamTotal> downStreamsDetails) {
this.downStreamsDetails = downStreamsDetails;
}
public GroupedDownStream() {
downStreamsDetails = new ArrayList<DownStreamTotal>();
}
}
The detail to display :
package tg.moov.imereport.dao;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "DownStreamTotal")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "DownStreamTotal.findAll", query = "SELECT d FROM DownStreamTotal d"),
#NamedQuery(name = "DownStreamTotal.findByDownStream", query = "SELECT d FROM DownStreamTotal d WHERE d.downStream = :downStream"),
#NamedQuery(name = "DownStreamTotal.findByNode", query = "SELECT d FROM DownStreamTotal d WHERE d.node = :node"),
#NamedQuery(name = "DownStreamTotal.findByTotalFiles", query = "SELECT d FROM DownStreamTotal d WHERE d.totalFiles = :totalFiles"),
#NamedQuery(name = "DownStreamTotal.findByMinDate", query = "SELECT d FROM DownStreamTotal d WHERE d.minDate = :minDate"),
#NamedQuery(name = "DownStreamTotal.findByMaxDate", query = "SELECT d FROM DownStreamTotal d WHERE d.maxDate = :maxDate")})
public class DownStreamTotal implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 10)
#Column(name = "DownStream")
private String downStream;
#Size(max = 15)
#Column(name = "Node")
private String node;
#Column(name = "TotalFiles")
private Integer totalFiles;
#Column(name = "MinDate")
#Temporal(TemporalType.DATE)
private Date minDate;
#Column(name = "MaxDate")
#Temporal(TemporalType.DATE)
private Date maxDate;
public DownStreamTotal() {
}
public DownStreamTotal(String downStream) {
this.downStream = downStream;
}
public String getDownStream() {
return downStream;
}
public void setDownStream(String downStream) {
this.downStream = downStream;
}
public String getNode() {
return node;
}
public void setNode(String node) {
this.node = node;
}
public Integer getTotalFiles() {
return totalFiles;
}
public void setTotalFiles(Integer totalFiles) {
this.totalFiles = totalFiles;
}
public Date getMinDate() {
return minDate;
}
public void setMinDate(Date minDate) {
this.minDate = minDate;
}
public Date getMaxDate() {
return maxDate;
}
public void setMaxDate(Date maxDate) {
this.maxDate = maxDate;
}
#Override
public int hashCode() {
int hash = 0;
hash += (downStream != null ? downStream.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof DownStreamTotal)) {
return false;
}
DownStreamTotal other = (DownStreamTotal) object;
if ((this.downStream == null && other.downStream != null) || (this.downStream != null && !this.downStream.equals(other.downStream))) {
return false;
}
return true;
}
#Override
public String toString() {
return "tg.moov.imereport.dao.DownStreamTotal[ downStream=" + downStream + " ]";
}
}
The primefaces code :
<p:commandButton action="#{groupedDataMBean.populateDownStreams}" value="search" ajax="false" update="downStreamTable" />
<p:dataTable id="downStreamTable" var="dwnStr" value="#{groupedDataMBean.groupedDownStreams}">
<f:facet name="header">
ImE Distribution Report
</f:facet>
<p:columnGroup type="header">
<p:row>
<p:column headerText="DownStream" />
<p:column headerText="#Files" />
<p:column headerText="MinDate" />
<p:column headerText="MaxDate" />
</p:row>
</p:columnGroup>
<p:subTable var="details" value="#{dwnStr.downStreamsDetails}">
<f:facet name="header">
#{dwnStr.downStream}
</f:facet>
<p:column>
#{details.node}
</p:column>
<p:column>
#{details.totalFiles}
</p:column>
<p:column>
#{details.minDate}
</p:column>
<p:column>
#{details.maxDate}
</p:column>
<p:columnGroup type="footer">
</p:columnGroup>
</p:subTable>
</p:dataTable>
Thank you in advance!
I found, something here about it. It is a Primefaces bug. They recommand to use nested datable instead.