primefaces row deleting from database - java

I'm trying to delete row in primefaces datatable from database. It's working fine in datatable, but after refreshing project the row value show up.I'm using http://www.mkyong.com/jsf2/how-to-delete-row-in-jsf-datatable/ example. Can anybody help?
index.xhtml
<p:growl id="messages" showDetail="true"/>
<p:dataTable var="u" value="#{logonTest.userList}" id="carList" editable="true">
<f:facet name="header">
In-Cell Editing
</f:facet>
<p:ajax event="rowEdit" listener="#{tableBean.onEdit}" update=":form:messages" />
<p:ajax event="rowEditCancel" listener="#{tableBean.onCancel}" update=":form:messages" />
<p:column headerText="Name" style="width:30%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{u.name}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{u.name}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Surname" style="width:20%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{u.surname}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{u.surname}" style="width:100%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Username" style="width:24%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{u.username}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{u.username}" style="width:100%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Description" style="width:20%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{u.description}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{u.description}" style="width:100%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:6%">
<p:rowEditor />
<h:commandLink value="Delete" action="#{logonTest.deleteAction(u)}" />
</p:column>
</p:dataTable>
</h:form>
LogonTest.java
#ViewScoped
#SessionScoped
#javax.faces.bean.ManagedBean(name = "logonTest")
public class LogonTest implements Serializable{
#PersistenceUnit(unitName="Webbeans_RESOURCE_LOCAL")
private EntityManagerFactory emf;
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
public List<User> userList = new ArrayList();
#PostConstruct
public void init(){
EntityManager em = emf.createEntityManager();
// Read the existing entries and write to console
Query q = em.createQuery("SELECT u FROM User u");
userList = q.getResultList();
System.out.println("Size: " + userList.size());
}
public LogonTest() {
}
public String deleteAction(User user) {
userList.remove(user);
return null;
}
}

that because you remove it from the arraylist only not from the database
use em.remove(user)

Your delete action is only removing it from the scoped variable.
public String deleteAction(User user) {
userList.remove(user);
return null;
}
You need to also remove it from the database, via the entity manager. em.remove(object)

Try the following code with EntityManager using remove method.
#ViewScoped
#SessionScoped
#javax.faces.bean.ManagedBean(name = "logonTest")
public class LogonTest implements Serializable{
#PersistenceUnit(unitName="Webbeans_RESOURCE_LOCAL")
private EntityManagerFactory emf;
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
public List<User> userList = new ArrayList();
#PostConstruct
public void init(){
EntityManager em = emf.createEntityManager();
// Read the existing entries and write to console
Query q = em.createQuery("SELECT u FROM User u");
userList = q.getResultList();
System.out.println("Size: " + userList.size());
}
public LogonTest() {
}
public String deleteAction(User user) {
EntityManager em = emf.createEntityManager();
em.remove(user);
userList.remove(user);
return null;
}
}

Related

Is it possible to filter a p:dataTable when filterBy is a List of Objects?

I'm using the component p:dataTable from Primefaces and I'm having a trouble to sort a list of objects.
I have a list of Emails and inside this list I have an other list with their email alias. This is my code:
public class Email {
private String idGoogle;
private String email;
public Email() {
}
public Email(String idGoogle, String email) {
this.idGoogle = idGoogle;
this.email = email;
}
public String getIdGoogle() {
return idGoogle;
}
public void setIdGoogle(String idGoogle) {
this.idGoogle = idGoogle;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
public class EmailSector extends Email implements Cloneable {
private Sector sector = new Sector();
private String password;
private String domain;
private String description;
private List<Email> aliasList = new ArrayList<>();
private List<EmailSector> emailSectorList = new ArrayList<>();
public EmailSector() {
}
...
<h:panelGroup id="emailsTable" >
<div class="emailsTable" >
<p:dataTable id="filterTable" var="item" value="#{emailSectorBean.sessionBean.itemPagina.emailSectorList}"
widgetVar="dataWidget"
emptyMessage="Nenhum registro encontrado com os dados buscados.">
<p:column filterBy="#{item.email}" headerText="E-Mail" filterMatchMode="contains"
filterValue="#{emailSectorBean.sessionBean.filtroAlteracao}">
<h:outputText value="#{item.email}" />
</p:column>
<p:column filterBy="#{item.description}" headerText="Descrição" filterMatchMode="contains">
<h:outputText value="#{item.description}" />
</p:column>
<p:column filterBy="#{item.sector.description}" headerText="sector" filterMatchMode="contains">
<h:outputText value="#{item.sector.description}" />
</p:column>
<p:column headerText="Alias" filterBy="#{item.listaAlias}" filterMatchMode="contains">
<h:dataTable var="alias" value="#{item.listaAlias}" >
<p:column>
<h:outputText value="#{alias.email}"/>
</p:column>
</h:dataTable>
</p:column>
</p:dataTable>
</div>
</h:panelGroup>
At this point:
<p:column headerText="Alias" filterBy="#{item.aliasList}" filterMatchMode="contains">
<h:dataTable var="alias" value="#{item.aliasList}" >
<p:column>
<h:outputText value="#{alias.email}"/>
</p:column>
</h:dataTable>
</p:column>
I print all the alias of an Email Sector. The problem is the type of aliasList is Email... So I would like to know if it's possible to use filterBy with a List and how can I got this working?
Thanks
I solved it by overriding the toString method, just like this:
#Override
public String toString() {
return this.email;
}
And then I called the toString method in the filterBy attribute:
<p:column headerText="Alias" filterBy="#{item.aliasList.toString()}" filterMatchMode="contains">
<h:dataTable var="alias" value="#{item.aliasList}" >
<p:column>
<h:outputText value="#{alias.email}"/>
</p:column>
</h:dataTable>
</p:column>
It worked fine!

Primefaces SelectCheckboxMenu null value

I'm trying to get selected values from a selectCheckboxMenu, but all I'm getting is null in the console. It doesn't work with selectOneMenu too. Here's my jsf form:
<h:form id="mmaster">
<p:dataTable
value="#{devicesBean.devices}"
var="dev"
widgetVar="dt"
border="1"
paginator="true"
paginatorPosition="top"
rows="10"
>
<f:facet name="header">Devices</f:facet>
<p:column headerText="UDN" sortBy="#{dev.deviceUDN}" filterBy="#{dev.deviceUDN}" filterMatchMode="contains" emptyMessage="No Devices Found">
<h:outputText value="#{dev.deviceUDN}" />
</p:column>
<p:column headerText="FriendlyName" sortBy="#{dev.deviceFriendlyName}" filterBy="#{dev.deviceFriendlyName}" filterMatchMode="contains">
<h:outputText value="#{dev.deviceFriendlyName}" />
</p:column>
<p:column headerText="Model" sortBy="#{dev.deviceModel}" filterBy="#{dev.deviceModel}" filterMatchMode="contains">
<h:outputText value="#{dev.deviceModel}" />
</p:column>
<p:column headerText="Manufacturer" sortBy="#{dev.deviceManufacturer}" filterBy="#{dev.deviceManufacturer}" filterMatchMode="contains">
<h:outputText value="#{dev.deviceManufacturer}" />
</p:column>
<p:column headerText="Type" sortBy="#{dev.deviceType}" filterBy="#{dev.deviceType}" filterMatchMode="contains">
<h:outputText value="#{dev.deviceType}" />
</p:column>
<p:column headerText="Actions">
<p:selectCheckboxMenu value="#{devicesBean.selectAnnotations}">
<f:selectItems value="#{devicesBean.annotations}" />
</p:selectCheckboxMenu>
</p:column>
<p:column>
<p:commandButton value="Annotate" action="#{devicesBean.doSave}" process="#this">
<f:setPropertyActionListener value="#{dev}" target="#{devicesBean.device}" />
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
I wonder if there is a problem in the bean's scope, And this is my managed bean:
#ManagedBean
public class DevicesBean implements Serializable {
private static final long serialVersionUID = 1L;
private List<Device> devices;
private List<String> annotations;
private List<String> selectAnnotations = new ArrayList<String>();
private Device device;
#EJB
IOntoProcessor iop;
#EJB
IDevicesDao idd;
public DevicesBean() {
}
#PostConstruct
public void init() {
setDevices(idd.getAllDevices());
setAnnotations(iop.getAllAnnotations());
}
public List<Device> getDevices() {
return devices;
}
public void setDevices(List<Device> devices) {
this.devices = devices;
}
public List<String> getAnnotations() {
return annotations;
}
public void setAnnotations(List<String> annotations) {
this.annotations = annotations;
}
public Device getDevice() {
return device;
}
public void setDevice(Device device) {
this.device = device;
}
public List<String> getSelectAnnotations() {
return selectAnnotations;
}
public void setSelectAnnotations(List<String> selectAnnotations) {
this.selectAnnotations = selectAnnotations;
}
public void doSave() {
System.out.println(selectAnnotations);
System.out.println(device);
selectAnnotations = new ArrayList<String>();
}
}
You are trying to submit the form through the Button with value Annotate, which has been specified to process itself only:
This will only process the button and its associated form parameters, and no other element within the form.
<p:commandButton value="Annotate" action="#{devicesBean.doSave}" process="#this">
<f:setPropertyActionListener value="#{dev}" target="#{devicesBean.device}" />
</p:commandButton>
Either remove the process="#this", or replace it with process="#form"
<p:commandButton value="Annotate" action="#{devicesBean.doSave}" process="#form">
<f:setPropertyActionListener value="#{dev}" target="#{devicesBean.device}" />
</p:commandButton>
Two, declare your managed bean scope: Either #RequestScope or #SessionScoped will work fine.

Datatable not refreshed after deleting or updating items

I was trying to implement sort functionality on primefaces dataTable.Sorting is working. But when I delete, update the dataTable items ,no effect (nothing changes) in dataTable. That is dataTable not getting cleared or refreshed.But in the database delete,update are occurring with out any issue.When I logged out and re-login, new list(dataTable) is fine.
employeeView.jsf:
<p:dataTable id="employees" value="#{employeeList.employees}"
var="employee" emptyMessage="No Employees found" rows="10"
paginator="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15" rowIndexVar="rowIndex">
<p:column sortBy="#{employee.firstName}">
<f:facet name="header">
<h:outputText value="First Name" />
</f:facet>
<h:outputText value="#{employee.firstName}">
</h:outputText>
</p:column>
<p:column sortBy="#{employee.lastName}">
<f:facet name="header">
<h:outputText value="Last Name" />
</f:facet>
<h:outputText value="#{employee.lastName}" />
</p:column>
</p:dataTable>
EmployeeList.java:
#Component("employeeList")
#SessionScoped
#Repository
public class EmployeeList implements Serializable {
private static final long serialVersionUID = -2417394435764260084L;
public static HibernateTemplate hibernateTemplate;
private List<Employee> employees = new ArrayList<Employee>();
#Autowired
public void setSessionFactory(SessionFactory sessionFactory)
{
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
public List<Employee> getEmployees() {
if(employees.isEmpty()){
employees.addAll(empList());
}
return employees;
}
#SuppressWarnings("unchecked")
public List<Employee> empList() {
try
{
List <Employee> result = hibernateTemplate.find("from Employee");
return result;
}
finally {
//close the session and user-supplied JDBC connection
}
}
}
I have tried with #RequestScope,#ViewScope etc.But no effect.Where I went wrong?
Primefaces-3.0.M3 with JSF2 and Google Cloud SQL

Why this table In-Cell editor, doesnt work?

I am trying to figure out, how the primefaces in-cell editor works.
For some reason, it does not work. I just see it activating and also i can type, but the values do not change. What is missing?
<?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:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:form>
<p:dataTable id="allSubjects" var="subject" value="#{subjectControllerUpdate.retrieve()}" paginator="true" rows="7" >
<p:column headerText="Name" sortBy="#{subject.name}" style="width:200px" >
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{subject.name}"/>
</f:facet>
<f:facet name="input">
<p:inputText value="#{subject.name}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column sortBy="#{subject.description}" headerText="Description">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{subject.description}"/>
</f:facet>
<f:facet name="input">
<p:inputText value="#{subject.description}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column sortBy="#{subject.credits}" headerText="Credits" style="width:50px">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{subject.credits}"/>
</f:facet>
<f:facet name="input">
<p:inputText value="#{subject.credits}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Options" style="width:50px">
<p:rowEditor />
</p:column>
</p:dataTable>
</h:form>
</html>
This is the managed bean
package controllers;
import crudfacades.SubjectFacade;
import entities.Subject;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
#Named("subjectControllerUpdate")
#SessionScoped
public class SubjectControllerUpdate implements Serializable {
private List<Subject> subjects;
private Subject currentSubject;
#EJB
private SubjectFacade ejbFacade;
//INITIALIZATION
public SubjectControllerUpdate() {
currentSubject = new Subject();
}
//RETRIEVE
public List<Subject> retrieve() {
return getSubjectFacade().findAll();
}
//UPDATE
//HELP METHODS
//RETURN THE FACADE FOR DATA MANIPULATION(Best practice)
private SubjectFacade getSubjectFacade() {
return ejbFacade;
}
//GETTERS AND SETTERS
public Subject getCurrentSubject() {
return currentSubject;
}
public void setCurrentSubject(Subject currentSubject) {
this.currentSubject = currentSubject;
}
public List<Subject> getSubjects() {
return subjects;
}
public void setSubjects(List<Subject> subjects) {
this.subjects = subjects;
}
}
but when i click comfirm, the value in the UI is not changed
You've bound the value of the <p:dataTable> to retrieve() instead of getSubjects(). So every single getter call will get the values straight from the DB instead of the model.
and i see no changes in the database
You are not saving anything in the DB.
Fix your controller as follows:
#Named
#SessionScoped
public class SubjectControllerUpdate implements Serializable {
private DataModel<Subject> subjects;
#EJB
private SubjectFacade ejbFacade;
#PostConstruct
public void init() {
subjects = new ListDataModel<Subject>(ejbFacade.findAll());
}
public void save() {
ejbFacade.save(subjects.getRowData());
}
public List<Subject> getSubjects() {
return subjects;
}
}
with
<h:form>
<p:dataTable value="#{subjectControllerUpdate.subjects}" ...>
        <p:ajax event="rowEdit" listener="#{subjectControllerUpdate.save}" />
...
</p:dataTable>
</h:form>
Using DataModel<Subject> instead of List<Subject> is necessary in order to be able to get the current row.

Issue rendering JPQL custom query results into a JSF page

I have an entity with the following named query:
#NamedQuery(name = "findAllGarbage", query = "SELECT g.filename, g.description, g.uploadDate FROM Garbage g;")
The problem is that i want to pass that result to a dataTable to render, and i recieve NumberFormatException. I dont understand why because there are no numbers anywhere.
This is how the rest of the program looks like:
-The EJB that executes the query
#Stateless(name = "ejbs/SearchEJB")
public class SearchEJB implements ISearchEJB {
#PersistenceContext
private EntityManager em;
public List<Garbage> findAllGarbage() {
Query query = em.createNamedQuery("findAllGarbage");
List<Garbage> tmpGarbage = query.getResultList();
return tmpGarbage;
}
-The part of the JSF that displays the tableData:
<p:dataTable var="garbage" value="#{resultsController.allGarbage}" paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<p:column>
<f:facet name="header">
<h:outputText value="Filename" />
</f:facet>
<h:outputText value="#{garbage.filename}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Description" />
</f:facet>
<h:outputText value="#{garbage.description}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Upload date" />
</f:facet>
<h:outputText value="#{garbage.uploadDate}" />
</p:column>
</p:dataTable>
-The managed bean that interacts with the JSF page:
#ManagedBean
#RequestScoped
public class ResultsController {
#EJB
private ISearchEJB searchEJB;
private Garbage garbage;
public List<Garbage> getAllGarbage() {
return searchEJB.findAllGarbage();
}
public Garbage getGarbage() {
return garbage;
}
public void setGarbage(Garbage garbage) {
this.garbage = garbage;
}
The error says:
WARNING: StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() for servlet Faces Servlet threw exception
java.lang.NumberFormatException: For input string: "filename"
I dont understand what is wrong with the file name.
------------------------------------UPDATE------------------------------------
I changed the JSF to this, and now i dont see the error. I see tha table data but empty:
<p:dataTable var="garbage" value="#{resultsController.allGarbage}" paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<p:column>
<f:facet name="header">
<h:outputText value="Filename" />
</f:facet>
<h:outputText value="#{garbage[4]}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Description" />
</f:facet>
<h:outputText value="#{garbage[3]}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Upload date" />
</f:facet>
<h:outputText value="#{garbage[6]}" />
</p:column>
</p:dataTable>
The problem is caused by the fact that a query such as
SELECT g.filename, g.description, g.uploadDate FROM Garbage
returns an Object[] with filename, description and uploadDate as its elements.
If you want to access them as object properties (as you do in JSF), you need to query for the full object instead:
SELECT g FROM Garbage g

Categories

Resources