Transactions in JSF Netbeans 7.3.1 generated code - jsf

I'm new to Java EE, following the learning by doing approach. In a very simple Mysql database with Netbeans 7.3.1 having a Patient table relates to a Person table, I'm having trouble understanding Netbeans generated code. I want to create a transaction where a Person and a Patient should be created and persisted with roll back possibility. Should i create a separate controller to handle such a transaction. Kindly help with a link to some similar example code. Code generated by Netbeans is below. (Some imports and redundant code removed)
Person.java
package entity;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
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.OneToMany;
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;
import javax.xml.bind.annotation.XmlTransient;
#Entity
#Table(name = "person")
#XmlRootElement
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "firstname")
private String firstname;
#Size(max = 255)
#Column(name = "email")
private String email;
#Size(max = 15)
#Column(name = "mobile")
private String mobile;
#Size(max = 15)
#Column(name = "residence")
private String residence;
#Size(max = 15)
#Column(name = "office")
private String office;
#Size(max = 255)
#Column(name = "address")
private String address;
#Size(max = 20)
#Column(name = "nic")
private String nic;
#Basic(optional = false)
#NotNull
#Column(name = "regdate")
#Temporal(TemporalType.DATE)
private Date regdate;
#Basic(optional = false)
#NotNull
#Column(name = "dob")
#Temporal(TemporalType.DATE)
private Date dob;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "lastname")
private String lastname;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 25)
#Column(name = "city")
private String city;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "personid")
private Collection<Patient> patientCollection;
public Person() {
}
public Person(Integer id) {
this.id = id;
}
public Person(Integer id, String firstname, Date regdate, Date dob, String lastname, String city) {
this.id = id;
this.firstname = firstname;
this.regdate = regdate;
this.dob = dob;
this.lastname = lastname;
this.city = city;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getResidence() {
return residence;
}
public void setResidence(String residence) {
this.residence = residence;
}
public String getOffice() {
return office;
}
public void setOffice(String office) {
this.office = office;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getNic() {
return nic;
}
public void setNic(String nic) {
this.nic = nic;
}
public Date getRegdate() {
return regdate;
}
public void setRegdate(Date regdate) {
this.regdate = regdate;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#XmlTransient
public Collection<Patient> getPatientCollection() {
return patientCollection;
}
public void setPatientCollection(Collection<Patient> patientCollection) {
this.patientCollection = patientCollection;
}
}
Patient.java
package entity;
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.JoinColumn;
import javax.persistence.ManyToOne;
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 = "patient")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Patient.findAll", query = "SELECT p FROM Patient p"),
#NamedQuery(name = "Patient.findById", query = "SELECT p FROM Patient p WHERE p.id = :id"),
#NamedQuery(name = "Patient.findByPatientcode", query = "SELECT p FROM Patient p WHERE p.patientcode = :patientcode"),
#NamedQuery(name = "Patient.findByHistory", query = "SELECT p FROM Patient p WHERE p.history = :history"),
#NamedQuery(name = "Patient.findByExtPatientCode", query = "SELECT p FROM Patient p WHERE p.extPatientCode = :extPatientCode")})
public class Patient implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 20)
#Column(name = "patientcode")
private String patientcode;
#Size(max = 255)
#Column(name = "history")
private String history;
#Size(max = 20)
#Column(name = "ExtPatientCode")
private String extPatientCode;
#JoinColumn(name = "personid", referencedColumnName = "id")
#ManyToOne(optional = false)
private Person personid;
public Patient() {
}
public Patient(Integer id) {
this.id = id;
}
public Patient(Integer id, String patientcode) {
this.id = id;
this.patientcode = patientcode;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPatientcode() {
return patientcode;
}
public void setPatientcode(String patientcode) {
this.patientcode = patientcode;
}
public String getHistory() {
return history;
}
public void setHistory(String history) {
this.history = history;
}
public String getExtPatientCode() {
return extPatientCode;
}
public void setExtPatientCode(String extPatientCode) {
this.extPatientCode = extPatientCode;
}
public Person getPersonid() {
return personid;
}
public void setPersonid(Person personid) {
this.personid = personid;
}
}
AbstractFacade.java
package session;
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]);
q.setFirstResult(range[0]);
return q.getResultList();
}
}
PatientFacade.java
package session;
import entity.Patient;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless
public class PatientFacade extends AbstractFacade<Patient> {
#PersistenceContext(unitName = "WebApplication4PU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public PatientFacade() {
super(Patient.class);
}
}
PersonFacade.java
package session;
import entity.Person;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless
public class PersonFacade extends AbstractFacade<Person> {
#PersistenceContext(unitName = "WebApplication4PU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public PersonFacade() {
super(Person.class);
}
}
PersonController.java
package controllers;
import entity.Person;
import controllers.util.JsfUtil;
import controllers.util.PaginationHelper;
import session.PersonFacade;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
#Named("personController")
#SessionScoped
public class PersonController implements Serializable {
private Person current;
private DataModel items = null;
#EJB
private session.PersonFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public PersonController() {
}
public Person getSelected() {
if (current == null) {
current = new Person();
selectedItemIndex = -1;
}
return current;
}
private PersonFacade getFacade() {
return ejbFacade;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getFacade().count();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Person) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Person();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PersonCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (Person) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PersonUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (Person) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getFacade().remove(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PersonDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getFacade().count();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
}
public Person getPerson(java.lang.Integer id) {
return ejbFacade.find(id);
}
#FacesConverter(forClass = Person.class)
public static class PersonControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
PersonController controller = (PersonController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "personController");
return controller.getPerson(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
}
}
PatientController.java
package controllers;
import entity.Patient;
import controllers.util.JsfUtil;
import controllers.util.PaginationHelper;
import session.PatientFacade;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
#Named("patientController")
#SessionScoped
public class PatientController implements Serializable {
private Patient current;
private DataModel items = null;
#EJB
private session.PatientFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public PatientController() {
}
public Patient getSelected() {
if (current == null) {
current = new Patient();
selectedItemIndex = -1;
}
return current;
}
private PatientFacade getFacade() {
return ejbFacade;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getFacade().count();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Patient) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Patient();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PatientCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (Patient) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PatientUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (Patient) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getFacade().remove(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PatientDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getFacade().count();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
}
public Patient getPatient(java.lang.Integer id) {
return ejbFacade.find(id);
}
#FacesConverter(forClass = Patient.class)
public static class PatientControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
PatientController controller = (PatientController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "patientController");
return controller.getPatient(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Patient) {
Patient o = (Patient) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Patient.class.getName());
}
}
}
}
Thanks in advance.

Fact: a single #Stateless EJB method call counts as a single full transaction.
Just make use of this fact. Create a new method in the #Stateless EJB which executes all necessary queries at once and then let your JSF backing bean call exactly that single method.
That's by the way exactly one of main reasons why EJBs exist: transparent transaction management. You seem to have missed this not unimportant fact while learning Java EE.

Related

Adding default namespace declarations using a generic list wrapper with JAXB

I am all new to JAXB and having wrecked my brains for a week over this I would like to ask the following question. How can I obtain default namespace declarations like these using a generic list wrapper as Blaise Doughan indroduced:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<departments xmlns="urn:example.org/departments">
<department>
<iddepartment>1</iddepartment>
<department>Deparment A</department>
<v_iddepartment>1</v_iddepartment>
</department>
<department>
<iddepartment>2</iddepartment>
<department>Department B</department>
<v_iddepartment>1</v_iddepartment>
</department>
</departments>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employees xmlns="urn:example.org/employees">
<employee>
<firstname>Tom</firstname>
<lastname>Jones</lastname>
<praefix>Dr.</praefix>
<birthdate>1970-01-01</birthdate>
<ipnumber>1234</ipnumber>
</employee>
<employee>
<firstname>Elvis</firstname>
<lastname>Knoxville</lastname>
<praefix/>
<birthdate>1970-01-02</birthdate>
<ipnumber>4567</ipnumber>
</employee>
</employees>
I have several annotated classes like these:
package org.bp24.server.table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name = "department", namespace = "urn:example.org/departments")
#XmlType(propOrder = {"iddepartment", "department", "v_iddepartment"})
public class Department {
private int iddepartment;
private String department;
private int v_iddepartment;
public int getIddepartment() {
return iddepartment;
}
public void setIddepartment(int iddepartment) {
this.iddepartment = iddepartment;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public int getV_iddepartment() {
return v_iddepartment;
}
public void setV_iddepartment(int v_iddepartment) {
this.v_iddepartment = v_iddepartment;
}
}
package org.bp24.server.table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name = "employee", namespace = "urn:example.org/employees")
#XmlType(propOrder = {"firstname", "lastname", "praefix", "suffix", "birthdate", "ipnumber"})
public class Employee {
private int idemployee;
private String firstname;
private String lastname;
private String praefix;
private String suffix;
private String birthdate;
private String ipnumber;
private int v_iduser;
#XmlTransient
public int getIdemployee() {
return idemployee;
}
public void setIdemployee(int idemployee) {
this.idemployee = idemployee;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getPraefix() {
return praefix;
}
public void setPraefix(String praefix) {
this.praefix = praefix;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getIpnumber() {
return ipnumber;
}
public void setIpnumber(String ipnumber) {
this.ipnumber = ipnumber;
}
#XmlTransient
public int getV_iduser() {
return v_iduser;
}
public void setV_iduser(int v_iduser) {
this.v_iduser = v_iduser;
}
}
Here is the list wrapper I use:
package org.bp24.server.xml.copy;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
public class GenericList <T> {
private List<T> list = new ArrayList<T>();
public GenericList() {
}
public GenericList(List<T> list) {
this.list = list;
}
public void add (T element){
list.add(element);
}
public boolean isEmpty(){
if(list.isEmpty()) return true;
return false;
}
public T get (int pos){
return list.get(pos);
}
#XmlAnyElement(lax=true)
public List<T> getList(){
return list;
}
}
And here is the marshalling code:
package org.bp24.server.xml.copy;
import java.util.HashMap;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;
import org.bp24.server.xml.GenericList;
public class MarshallMatters<T> {
private static volatile HashMap<Class, JAXBContext> contextStore = new HashMap<Class, JAXBContext>();
//synchronized to ensure orderly concurrent contextStore access
private synchronized JAXBContext getContext (Class clazz) throws JAXBException{
if(contextStore.containsKey(clazz)) return contextStore.get(clazz);
JAXBContext context = JAXBContext.newInstance(GenericList.class, clazz);
contextStore.put(clazz, context);
return context;
}
private Class getClassFromList(List<T> list){
if(!list.isEmpty()) return list.get(0).getClass();
return null;
}
public void writeXml(List<T> list) throws JAXBException{
Class clazz = getClassFromList(list);
if(clazz==null){
System.out.println("Error message");
return;
}
JAXBContext jc = getContext(clazz);
GenericList<T> genList = new GenericList<T>(list);
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
QName qn = new QName(clazz.getSimpleName().toLowerCase() + "s");
JAXBElement<GenericList> jaxbe = new JAXBElement<GenericList>(qn, GenericList.class, genList);
m.marshal(jaxbe, System.out);
}
public void readXml(List<T> list) throws JAXBException{
...
}
}
Thank you very much in advance for your help.

JSF Updating a selectOneMenu based on another one

I'm new to JSF, and stuck in a problem.
I have a selectOneMenu for displaying the list of countries. When the user selects one of the country, there's another selectOneMenu having the cities (=regions in my case) should be auto-populated.
I tried several iterations for doing the same but didn't help.
Please let me know if anything else is also needed to help me. Would really appreciate it.
UPDATE:
Here's the code after adding listener:
<p:outputLabel for="countryRegistration">#{msg['country']}:</p:outputLabel>
<p:selectOneMenu id="countryRegistration" value="#{mbcActor.geoData.country}" style="width:120px;" >
<f:attribute name="country" value="java.util.List" />
<f:converter converterId="ViewScopedObjectConverter"/>
<f:selectItem itemLabel="#{msg['selectCountry']}" itemValue=""/>
<f:selectItems value="#{geoLists.countryList}" var="country" itemLabel="#{country.name}"/>
<p:ajax listener="#{mbcActor.geoData.updateRegions}" render="cityRegistration"/>
</p:selectOneMenu>
<p:message for="countryRegistration"/>
<p:outputLabel for="cityRegistration">#{msg['city']}:</p:outputLabel>
<p:selectOneMenu id="cityRegistration" value="#{mbcActor.geoData.region}" style="width:120px;">
<f:attribute name="regions" value="java.util.List" />
<f:converter converterId="ViewScopedObjectConverter"/>
<f:selectItem itemLabel="#{msg['selectCity']}" itemValue=""/>
<!--<f:selectItems value="#{geoLists.regionForCountry}" var="region" itemLabel="#{region.name}"/>-->
<f:selectItems value="#{geoLists.getRegionForCountry(country)}" var="region" itemLabel="#{region.description}"/>
</p:selectOneMenu>
<p:message for="cityRegistration"/>
But it says:
Oct 05, 2013 2:04:53 AM com.sun.faces.lifecycle.InvokeApplicationPhase execute
WARNING: Target Unreachable, identifier 'mbcActor' resolved to null
javax.el.PropertyNotFoundException: Target Unreachable, identifier 'mbcActor' resolved to null
at org.apache.el.parser.AstValue.getTarget(AstValue.java:98)
at org.apache.el.parser.AstValue.invoke(AstValue.java:259)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:39)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at org.primefaces.component.behavior.ajax.AjaxBehaviorListenerImpl.processCustomListener(AjaxBehaviorListenerImpl.java:70)
at org.primefaces.component.behavior.ajax.AjaxBehaviorListenerImpl.processArgListener(AjaxBehaviorListenerImpl.java:59)
at org.primefaces.component.behavior.ajax.AjaxBehaviorListenerImpl.processAjaxBehavior(AjaxBehaviorListenerImpl.java:47)
Beans:
package xxx.core.entities;
// Generated Oct 20, 2009 11:07:18 AM by Hibernate Tools 3.2.2.GA
import javax.faces.event.ValueChangeEvent;
import javax.inject.Inject;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import static javax.persistence.GenerationType.IDENTITY;
/**
* DataActorGeo
*/
#Entity
#Table(name = "dataActorGeo")
// #org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
#Access(AccessType.PROPERTY)
public class DataActorGeo implements java.io.Serializable {
private Integer id;
private Country country;
private Region region;
private String city;
private String province;
private String address;
private String addressLine2;
private String postCode;
private String nationality;
private String phone1;
private String phone2;
private Double latitude;
private Double longitude;
private Actor actor;
private List<Region> regions;
#Inject
EntityManager entityManager;
public void updateRegions() {
//Country ctry = (Country) event.getNewValue();
try{
System.out.println("bbbbbbbbbbbbbbbbbbbbbbb" + country.toString());
// if (regions == null) {
this.regions = entityManager.createQuery("select r From Region r Where r.country.id = :countryId order by r.description ")
.setParameter("countryId", country.getId())
.getResultList();
//countryIdCache = country.getId();
// }
System.out.println("aaaaaaaaaaa" + regions.toString());
} catch(Exception e){System.out.println("cccccccccc"); }//return new ArrayList<Region>(); }
//return regions;
}
public DataActorGeo() {
}
public DataActorGeo(Country country, String city) {
this.country = country;
this.city = city;
}
public DataActorGeo(Country country, Region region, String city, String address, String postCode, String phone1, String phone2, Actor actor) {
this.country = country;
this.region = region;
this.city = city;
this.address = address;
this.postCode = postCode;
this.phone1 = phone1;
this.phone2 = phone2;
this.actor = actor;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "Country")
// #IndexedEmbedded(prefix = "country.")
public Country getCountry() {
return this.country;
}
public void setCountry(Country country) {
this.country = country;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "Region")
// #IndexedEmbedded(prefix = "region.")
public Region getRegion() {
return this.region;
}
public void setRegion(Region region) {
this.region = region;
}
public List<Region> getRegions()
{
return this.regions;
}
public void setRegions(List<Region> regions)
{
this.regions=regions;
}
#Column(name = "City")
// //#Field(index = Index.UN_TOKENIZED)
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
#Column(name = "province")
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
#Column(name = "address")
// //#Field(index = Index.TOKENIZED)
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
#Column(name = "addressLine2")
// //#Field(index = Index.TOKENIZED)
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
#Column(name = "postCode")
// //#Field(index = Index.UN_TOKENIZED)
public String getPostCode() {
return this.postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
#Column(name = "nationality")
// //#Field(index = Index.UN_TOKENIZED)
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
#Column(name = "phone1")
// //#Field(index = Index.UN_TOKENIZED)
public String getPhone1() {
return phone1;
}
public void setPhone1(String phone1) {
this.phone1 = phone1;
}
#Column(name = "phone2")
// //#Field(index = Index.UN_TOKENIZED)
public String getPhone2() {
return phone2;
}
public void setPhone2(String phone2) {
this.phone2 = phone2;
}
#OneToOne(mappedBy = "geoData")
public Actor getActor() {
return actor;
}
public void setActor(Actor actor) {
this.actor = actor;
}
#Column(name = "latitude")
public Double getLatitude() {
return latitude;
}
#Column(name = "longitude")
public Double getLongitude() {
return longitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
}
package xxx.lists;
import xxx.application.configuration.ISNetApp;
import xxx.core.entities.Country;
import xxx.core.entities.Region;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
#Named
#ViewScoped
public class GeoLists implements Serializable {
#Inject
EntityManager entityManager;
#Inject
ISNetApp sNetApp;
private List<Country> countryList;
public List<Country> getCountryList() {
if (countryList == null) {
String query = "select c from Country c order by c.ordering, c.name";
countryList = (List<Country>) entityManager.createQuery(query).getResultList();
}
return countryList;
}
public void setCountryList(List<Country> countryList) {
this.countryList = countryList;
}
private List<Country> deliveryCountryList;
public List<Country> getDeliveryCountryList() {
if (deliveryCountryList == null) {
String query = "select c from Country c where c.groups LIKE '%D,%' order by c.ordering, c.name";
deliveryCountryList = (List<Country>) entityManager.createQuery(query).getResultList();
}
return deliveryCountryList;
}
public void setDeliveryCountryList(List<Country> deliveryCountryList) {
this.deliveryCountryList = deliveryCountryList;
}
public Country getCountryByIsoCode2(String isoCode2) {
String query = "select c from Country c where c.isoCode2=:ic";
try {
return (Country) entityManager.createQuery(query).setParameter("ic", isoCode2).getSingleResult();
} catch (NoResultException e) {
return null;
}
}
private List<Region> regionForCountry;
private int countryIdCache;
private List<Region> regions;
public List<Region> getRegions(){
return this.regions;
}
public void setRegions(List<Region> regions){
this.regions = regions;
}
public List<Region> getRegionForCountryById(Long countryId) {
Country country = entityManager.find(Country.class, countryId.intValue());
return getRegionForCountry(country);
}
public List<Region> getRegionForCountry(Country country) {
try{
System.out.println("bbbbbbbbbbbbbbbbbbbbbbb" + country.toString());
//if (regionForCountry == null || countryIdCache != country.getId()) {
regionForCountry = entityManager.createQuery("select r From Region r Where r.country.id = :countryId order by r.description ")
.setParameter("countryId", 1)//country.getId())
.getResultList();
// countryIdCache = country.getId();
//}
// System.out.println("aaaaaaaaaaa" + regionForCountry.toString());
} catch(Exception e){System.out.println("cccccccccc"); return new ArrayList<Region>(); }
return regionForCountry;
}
public void setRegionForCountry(List<Region> regionForCountry) {
this.regionForCountry = regionForCountry;
}
private Country mainCountry;
private Country country;
public void setCountry(Country country) {
this.country=country;
}
public Country getCountry(){
return this.country;
}
public Country getMainCountry() {
if (mainCountry == null) {
mainCountry = entityManager.find(Country.class, sNetApp.getMainCountryId());
}
return mainCountry;
}
public void setMainCountry(Country mainCountry) {
this.mainCountry = mainCountry;
}
private List<Country> specificGroupCountryList;
private String groupCache;
public List<Country> getSpecificGroupCountryList(String group) {
if (specificGroupCountryList == null || groupCache == null || groupCache.compareTo(group) != 0) {
String query = "from Country where groups LIKE '%" + group + ",%' order by ordering, name";
specificGroupCountryList = (List<Country>) entityManager.createQuery(query).getResultList();
}
return specificGroupCountryList;
}
public void setSpecificGroupCountryList(List<Country> specificGroupCountryList) {
this.specificGroupCountryList = specificGroupCountryList;
}
}
mbcActor is a param defined as:
<ui:param name="mbcActor" value="#{registrationHelper.newActor}"/>
AbstractActor:
#MappedSuperclass
public class AbstractActor extends AbstractGenericElement implements java.io.Serializable, IGenericElement, EmailContact {
private static Logger log = LoggerFactory.getLogger(AbstractActor.class);
public static enum Gender {
Male,
Female
}
/**
* Transient
*/
private boolean selected;
private Integer id;
private Long version;
private byte type;
private String language;
private byte status;
private byte publicStatus;
private String permalink;
private Boolean customPermalink;
private String displayName;
private String forename;
private String surname;
private Gender gender;
private Date birthday;
private String mobile;
private Byte subType;
private String stringValue1;
private String stringValue2;
private String stringValue3;
#Transient
#XmlTransient
private Integer age;
private String profileMessage;
private String statusMessage;
private String email;
private String username;
private String passwordHash;
private int passwordHashIterations;
private String salt;
private String timezone;
private String activationCode;
private Boolean activationEmailSent;
private Integer completitionPercentage;
private Integer ordering;
// Stats
private ActorStats stats;
// Extensions
private DataActorGeo geoData;
private DataActorExtended dataActorExtended;
private Boolean acceptNewsletter;
private Boolean emailAlertsEnabled;
private Set<ActorTag> actorTags = new HashSet<ActorTag>(0);
private List<Role> roles = new ArrayList<Role>(0);
private Actor newDataToBeModerated;
private Date expireDate;
private Integer points;
private BigDecimal wallet;
private Byte emailAlertsType;
private Byte emailOffersType;
private String emailHash;
// Data blob
private byte[] data;
private Set<ActorInCategory> actorInCategories = new HashSet<ActorInCategory>(
0);
private List<ActorAttribute> actorAttributes = new ArrayList<ActorAttribute>(0);
public AbstractActor() {
this.version = 1l;
this.activationEmailSent = false;
this.acceptNewsletter = true;
this.emailAlertsEnabled = true;
this.completitionPercentage = 0;
this.customPermalink = false;
this.wallet = new BigDecimal(0);
this.points = 0;
this.emailAlertsType = ActorConstants.RECURRING_EMAIL_TYPE_NONE;
this.emailOffersType = ActorConstants.RECURRING_EMAIL_TYPE_NONE;
}
public AbstractActor(byte type, byte status) {
this.version = 1l;
this.type = type;
this.status = status;
this.publicStatus = ActorConstants.PUBLIC_STATUS_OFFLINE;
this.activationEmailSent = false;
this.acceptNewsletter = true;
this.emailAlertsEnabled = true;
this.completitionPercentage = 0;
this.customPermalink = false;
this.wallet = new BigDecimal(0);
this.points = 0;
this.emailAlertsType = ActorConstants.RECURRING_EMAIL_TYPE_NONE;
this.emailOffersType = ActorConstants.RECURRING_EMAIL_TYPE_NONE;
}
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "geoData", nullable = true)
#org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public DataActorGeo getGeoData() {
return this.geoData;
}
public void setGeoData(DataActorGeo geoData) {
this.geoData = geoData;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "actor")
public Set<ActorInCategory> getActorInCategories() {
return this.actorInCategories;
}
public void setActorInCategories(Set<ActorInCategory> actorInCategories) {
this.actorInCategories = actorInCategories;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "actor")
public List<ActorAttribute> getActorAttributes() {
return this.actorAttributes;
}
public void setActorAttributes(List<ActorAttribute> actorAttributes) {
this.actorAttributes = actorAttributes;
}
}
Your <p:ajax> tag uses the render attribute, which isn't predefined. The attribute you want is update.
supposing that registrationHelper.newActor is an instance of of a Managed Bean, I think it's probably not initialized. Why don't you make sure it is, by creating it on RegistrationHelper's PostConstruct, or even get it through a method like
public AbstractActor createNewActor() {
newActor = new AbstractActor();
return newActor;
}
<ui:param name="mbcActor" value="#{registrationHelper.createNewActor}"/>

#ManagedProperty - access properties Injected from one view scoped bean into another view scoped bean

I have injected one view scoped bean into another view scoped bean , and I can access some properties of the first bean but others appear as null in #PostContruct. How can I see their real value?
Thanks in advance
Update:
I can only see the value of properties updated in #PostContruct of the first bean and not others
Bean 1(SelectOfferMpans)
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sofyc.backingbean.offer;
import es.iberdrola.configuration.LogginManager;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
import org.apache.log4j.Logger;
import sofyc.bean.BeanInstanceLocator;
import sofyc.bean.IOffersBean;
import sofyc.corejsf.SofycNavigation;
import sofyc.corejsf.SofycParamNames;
import sofyc.utils.JSFHelper;
import sofyc.valueobject.CustomerFindVO;
import sofyc.valueobject.MpanVO;
import sofyc.valueobject.OfferSitesVO;
#ManagedBean
#ViewScoped
public class SelectOfferMpans implements Serializable{
/**
* Logger.
*/
private static Logger log = LogginManager.getLogger(SelectOfferMpans.class.getName());
static {
adq_ren_types = new String[2];
}
private final String ID_OFFER_SELECT_MPANS_FORM = "selectMpans";
private String menuOrigin;
/**
* Parametro de busqueda del formulario.
*/
private String registrationNumber;
private List<CustomerFindVO> customerfoundList;
private CustomerFindVO customerfound;
private String companyRegNo;
private String customerId;
private CustomerFindVO selectedCustomer;
private List<OfferSitesVO> offerSites;
private List<OfferSitesVO> filteredSites;
private OfferSitesVO selectedSite;
private OfferSitesVO[] selectedSites;
private List<MpanVO> siteMpans;
private SelectItem[] hh_nhh_List;
private SelectItem[] adq_ren_List;
private final static String[] adq_ren_types;
private Map<String,String> hh_nhh_types;
public Map<String, String> getHh_nhh_types() {
return hh_nhh_types;
}
public void setHh_nhh_types(Map<String, String> hh_nhh_types) {
this.hh_nhh_types = hh_nhh_types;
}
public SelectItem[] getHh_nhh_List() {
return hh_nhh_List;
}
public void setHh_nhh_List(SelectItem[] hh_nhh_List) {
this.hh_nhh_List = hh_nhh_List;
}
public SelectItem[] getAdq_ren_List() {
return adq_ren_List;
}
public void setAdq_ren_List(SelectItem[] adq_ren_List) {
this.adq_ren_List = adq_ren_List;
}
public List<OfferSitesVO> getOfferSites() {
return offerSites;
}
public void setOfferSites(List<OfferSitesVO> offerSites) {
this.offerSites = offerSites;
}
public List<OfferSitesVO> getFilteredSites() {
return filteredSites;
}
public void setFilteredSites(List<OfferSitesVO> filteredSites) {
this.filteredSites = filteredSites;
}
public OfferSitesVO getSelectedSite() {
return selectedSite;
}
public void setSelectedSite(OfferSitesVO selectedSite) {
this.selectedSite = selectedSite;
}
public OfferSitesVO[] getSelectedSites() {
return selectedSites;
}
public void setSelectedSites(OfferSitesVO[] selectedSites) {
this.selectedSites = selectedSites;
}
public List<MpanVO> getSiteMpans() {
return siteMpans;
}
public void setSiteMpans(List<MpanVO> siteMpans) {
this.siteMpans = siteMpans;
}
public CustomerFindVO getSelectedCustomer() {
return selectedCustomer;
}
public void setSelectedCustomer(CustomerFindVO selectedCustomer) {
this.selectedCustomer = selectedCustomer;
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getCompanyRegNo() {
return companyRegNo;
}
public void setCompanyRegNo(String companyRegNo) {
this.companyRegNo = companyRegNo;
}
public List<CustomerFindVO> getCustomerfoundList() {
return customerfoundList;
}
public void setCustomerfoundList(List<CustomerFindVO> customerfoundList) {
this.customerfoundList = customerfoundList;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public void setRegistrationNumber(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public CustomerFindVO getCustomerfound() {
return customerfound;
}
public void setCustomerfound(CustomerFindVO customerfound) {
this.customerfound = customerfound;
}
public String getMenuOrigin() {
return menuOrigin;
}
public void setMenuOrigin(String menuOrigin) {
this.menuOrigin = menuOrigin;
}
/**
* Creates a new instance of SelectOfferMpans
*/
public SelectOfferMpans() {
}
#PostConstruct
public void init() {
try{
if(log.isDebugEnabled()) {
log.debug("INIT");
}
if (getMenuOrigin() == null) {
setMenuOrigin(JSFHelper.getParameterFromView("OPTION"));
if (getMenuOrigin() == null) {
setMenuOrigin((String) JSFHelper.getParameterFromRequest("OPTION"));
}
if (log.isDebugEnabled()) {
log.debug("CREATE OFFER --> guardado en VIEW VAR menuOrigin el "
+ "valor recuperado en la Request del parametro OPTION:: "
+ getMenuOrigin());
}
}
adq_ren_types[0] = "Adquisitions";
adq_ren_types[1] = "Renews";
this.setHh_nhh_types(cargaHHNHH());
//hh_nhh_List = createFilterOptions(hh_nhh_types);
hh_nhh_List = createFilterOptions1(hh_nhh_types,true);
adq_ren_List = createFilterOptions(adq_ren_types);
}catch(Exception e)
{
log.error("SearchCustomer:Init", e);
JSFHelper.addErrorMessage("messagesError", e.getMessage());
}
}
public void findCustomer() throws Exception {
CustomerFindVO customer=null;
try{
if (log.isDebugEnabled()) {
log.debug("Searching Customer....");
}
IOffersBean offersBean = BeanInstanceLocator.getOffersBean();
customerfound = offersBean.searchCustomer(companyRegNo);
if (customerfound!=null){
this.setOfferSites(offersBean.getCustomerSites(customerfound.getCustomerId()));
}
else{
this.setOfferSites(null);
JSFHelper.addErrorMessage(ID_OFFER_SELECT_MPANS_FORM, "Error searching customer");
}
if (log.isDebugEnabled()) {
log.debug("Customer Data Found");
}
} catch (Throwable t) {
log.error("findCustomer:", t);
JSFHelper.addErrorMessage(ID_OFFER_SELECT_MPANS_FORM, "Error searching customer");
}
}
public String goToOffers(){
try{
JSFHelper.addParamToRequest(SofycParamNames.CUSTOMER_ID, customerfound.getCustomerId());
JSFHelper.addParamToRequest(SofycParamNames.OPTION, this.getMenuOrigin());
return SofycNavigation.VIEW_CREATE_OFFERS_PAGE;
} catch (Throwable t) {
log.error("goToOffers:", t);
JSFHelper.addErrorMessage(ID_OFFER_SELECT_MPANS_FORM, "Error navigating to offers page");
return null;
}
}
private SelectItem[] createFilterOptions(String[] data) {
SelectItem[] options = new SelectItem[data.length + 1];
options[0] = new SelectItem("", "Select");
for(int i = 0; i < data.length; i++) {
options[i + 1] = new SelectItem(data[i], data[i]);
}
return options;
}
private SelectItem[] createFilterOptions1(Map<String,String> data, boolean select) {
//SelectItem[] options = new SelectItem[data.size() + 1];
SelectItem[] options;
int i = 0;
if (select==true) {
options = new SelectItem[data.size() + 1];
options[i] = new SelectItem("", "Select");
i++;
}
else{
options = new SelectItem[data.size()];
}
for (Map.Entry e: data.entrySet()) {
options[i] = new SelectItem(e.getKey().toString(), e.getValue().toString());
//options[i + 1] = new SelectItem(e.getValue().toString(),e.getKey().toString());
i++;
}
return options;
}
private Map<String,String> cargaHHNHH() {
Map<String,String> hh_nhh_types= new HashMap<String,String>();
hh_nhh_types.put("HH","HH");
hh_nhh_types.put("NHH","NHH");
return hh_nhh_types;
}
}
Bean 2(CreateOffer) property selectedSites of the first bean appears always as null and It's loaded in findCustomer Method.
package sofyc.backingbean.offer;
import es.iberdrola.configuration.LogginManager;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.apache.log4j.Logger;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.ToggleEvent;
import org.primefaces.event.UnselectEvent;
import sofyc.bean.BeanInstanceLocator;
import sofyc.bean.IOffersBean;
import sofyc.utils.JSFHelper;
import sofyc.valueobject.CustomerVO;
import sofyc.valueobject.MddMeasurementClassVO;
import sofyc.valueobject.MpanVO;
import sofyc.valueobject.OfferSitesVO;
import sofyc.valueobject.ProfileClassVO;
import sofyc.valueobject.SiteVO;
import sofyc.valueobject.TradebookVO;
#ManagedBean
#ViewScoped
public class CreateOffer implements Serializable {
private static Logger log = LogginManager.getLogger(CreateOffer.class.getName());
/**
* Creates a new instance of CreateOffer
*/
static {
adq_ren_types = new String[2];
}
#ManagedProperty(value="#{selectOfferMpans.selectedSites}")
//#ManagedProperty(value="#{selectOfferMpans}")
//private SelectOfferMpans selectOfferMpans;
private OfferSitesVO[] selectedSites;
/*public void setSelectOfferMpans(SelectOfferMpans selectOfferMpans) {
this.selectOfferMpans = selectOfferMpans;
}*/
public void setSelectedSites(OfferSitesVO[] selectedSites) {
this.selectedSites = selectedSites;
}
/**
* Valores posibles de donde viene la pagina.
*/
private final String CREATE_OFFERS_OPTION = "CREATE";
private final String OFFERS_OPTION = "OFFERS";
private String menuOrigin;
/**
* Corresponde a la columna CUSTOMER_ID.
*/
private Integer customerId;
private Map<String,String> managers;
private Date offerFromDate;
private Date offerToDate;
private Date expiryDate;
private Integer tradeBookId;
private String creditScore;
private String consultantMargin;
private String spMargin;
private Integer productId;
private Integer profileClassId;
private String measurementClassId;
private Integer curveId;
/**
* Customer selected.
*/
private CustomerVO customer;
private List<OfferSitesVO> offerSites;
private List<OfferSitesVO> filteredSites;
private OfferSitesVO selectedSite;
private OfferSitesVO[] selectedSites1;
public OfferSitesVO[] getSelectedSites1() {
return selectedSites1;
}
public void setSelectedSites1(OfferSitesVO[] selectedSites1) {
this.selectedSites1 = selectedSites1;
}
private List<MpanVO> siteMpans;
//private final static String[] hh_nhh_types;
private Map<String,String> hh_nhh_types;
private final static String[] adq_ren_types;
//private final static String[] cotOfferTypes;
private Map<String,String> cotOfferTypes;
private Map<String,String> offerType;
private Map<String,String> loadCurve;
//private final static String[] offerType;
//private final static String[] loadCurve;
private SelectItem[] hh_nhh_List;
private SelectItem[] adq_ren_List;
private SelectItem[] cotOfferList;
private String cotOfferSelection;
private String comcOfferSelection;
private String copcOfferSelection;
private String offerTypeSelection;
private String loadCurveSelection;
//La oferta es de tipo HH o NHH
private String offerHH_NHH;
private SelectItem[] offerTypeList;
private SelectItem[] loadCurveList;
/**
* Site selected.
*/
private SiteVO site;
private MpanVO mpan;
private List<SiteVO> sites;
private List<MpanVO> mpans;
private List<TradebookVO> tradeBookList;
private Map<String,Integer> ProductList;
private List<ProfileClassVO> profileClassList;
private List<MddMeasurementClassVO> measurementClassList;
private Map<String,Integer> CurveList;
#PostConstruct
public void init() {
if(log.isDebugEnabled()) {
log.debug("********************** CreateOffer::init **********************");
}
if (getMenuOrigin() == null) {
setMenuOrigin(JSFHelper.getParameterFromView("OPTION"));
if (getMenuOrigin() == null) {
setMenuOrigin((String) JSFHelper.getParameterFromRequest("OPTION"));
}
if (log.isDebugEnabled()) {
log.debug("CREATE OFFER --> guardado en VIEW VAR menuOrigin el "
+ "valor recuperado en la Request del parametro OPTION:: "
+ getMenuOrigin());
}
}
adq_ren_types[0] = "Adquisitions";
adq_ren_types[1] = "Renews";
//Valor por defecto de COT
cotOfferSelection="0";
//Valor por defecto de COMC
comcOfferSelection="0";
//Valor por defecto de COPC
copcOfferSelection="0";
//Valor por defecto de OfferType
offerTypeSelection="0";
//Valor por defecto de loadCurve
loadCurveSelection="0";
offerHH_NHH="NHH";
this.setHh_nhh_types(cargaHHNHH());
//hh_nhh_List = createFilterOptions(hh_nhh_types);
hh_nhh_List = createFilterOptions1(hh_nhh_types,true);
adq_ren_List = createFilterOptions(adq_ren_types);
//cotOfferList = createFilterOptions(cotOfferTypes);
this.setCotOfferTypes(cargaCOT());
cotOfferList = createFilterOptions1(cotOfferTypes,false);
this.setOfferType(cargaofferType());
offerTypeList = createFilterOptions1(offerType,false);
this.setLoadCurve(cargaloadCurve());
loadCurveList = createFilterOptions1(loadCurve,false);
populateRequestParamsInViewVars();
initCustomerInfo();
CurveList = new LinkedHashMap<String,Integer>();
ProductList = new LinkedHashMap<String,Integer>();
//hh_nhh_List = new LinkedHashMap<String,Integer>();
profileClassId=2;
measurementClassId="A";
curveId=1;
tradeBookId=3;
profileClassList = new ArrayList<ProfileClassVO>();
measurementClassList = new ArrayList<MddMeasurementClassVO>();
tradeBookList = new ArrayList<TradebookVO>();
loadProfileClass();
loadMeasurementClass();
loadTradeBook();
}
public void onRowSelect(SelectEvent event) {
//FacesMessage msg = new FacesMessage("Car Selected", ((Car) event.getObject()).getModel());
//FacesContext.getCurrentInstance().addMessage(null, msg);
//event.getComponent().
}
public void onRowUnselect(UnselectEvent event) {
//FacesMessage msg = new FacesMessage("Car Unselected", ((Car) event.getObject()).getModel());
//FacesContext.getCurrentInstance().addMessage(null, msg);
}
public String getOfferTypeSelection() {
return offerTypeSelection;
}
public void setOfferTypeSelection(String offerTypeSelection) {
this.offerTypeSelection = offerTypeSelection;
}
public String getLoadCurveSelection() {
return loadCurveSelection;
}
public void setLoadCurveSelection(String loadCurveSelection) {
this.loadCurveSelection = loadCurveSelection;
}
public SelectItem[] getOfferTypeList() {
return offerTypeList;
}
public void setOfferTypeList(SelectItem[] offerTypeList) {
this.offerTypeList = offerTypeList;
}
public SelectItem[] getLoadCurveList() {
return loadCurveList;
}
public void setLoadCurveList(SelectItem[] loadCurveList) {
this.loadCurveList = loadCurveList;
}
public List<ProfileClassVO> getProfileClassList() {
return profileClassList;
}
public void setProfileClassList(List<ProfileClassVO> ProfileClassList) {
this.profileClassList = ProfileClassList;
}
public MpanVO getMpan() {
return mpan;
}
public void setMpan(MpanVO mpan) {
this.mpan = mpan;
}
public List<MpanVO> getMpans() {
return mpans;
}
public void setMpans(List<MpanVO> mpans) {
this.mpans = mpans;
}
public List<SiteVO> getSites() {
return sites;
}
public void setSites(List<SiteVO> sites) {
this.sites = sites;
}
public CustomerVO getCustomer() {
return customer;
}
public void setCustomer(CustomerVO customer) {
this.customer = customer;
}
public SiteVO getSite() {
return site;
}
public void setSite(SiteVO site) {
this.site = site;
}
public String getCreditScore() {
return creditScore;
}
public void setCreditScore(String creditScore) {
this.creditScore = creditScore;
}
public String getConsultantMargin() {
return consultantMargin;
}
public void setConsultantMargin(String consultantMargin) {
this.consultantMargin = consultantMargin;
}
public String getSpMargin() {
return spMargin;
}
public void setSpMargin(String spMargin) {
this.spMargin = spMargin;
}
public List<OfferSitesVO> getOfferSites() {
return offerSites;
}
public void setOfferSites(List<OfferSitesVO> offerSites) {
this.offerSites = offerSites;
}
public List<OfferSitesVO> getFilteredSites() {
return filteredSites;
}
public void setFilteredSites(List<OfferSitesVO> filteredSites) {
this.filteredSites = filteredSites;
}
public SelectItem[] getAdq_ren_List() {
return adq_ren_List;
}
public void setAdq_ren_List(SelectItem[] adq_ren_List) {
this.adq_ren_List = adq_ren_List;
}
public SelectItem[] getHh_nhh_List() {
return hh_nhh_List;
}
public void setHh_nhh_List(SelectItem[] hh_nhh_List) {
this.hh_nhh_List = hh_nhh_List;
}
public Map<String, String> getHh_nhh_types() {
return hh_nhh_types;
}
public void setHh_nhh_types(Map<String, String> hh_nhh_types) {
this.hh_nhh_types = hh_nhh_types;
}
public Map<String, String> getOfferType() {
return offerType;
}
public void setOfferType(Map<String, String> offerType) {
this.offerType = offerType;
}
public Map<String, String> getLoadCurve() {
return loadCurve;
}
public void setLoadCurve(Map<String, String> loadCurve) {
this.loadCurve = loadCurve;
}
public String getOfferHH_NHH() {
return offerHH_NHH;
}
public void setOfferHH_NHH(String OfferHH_NHH) {
this.offerHH_NHH = OfferHH_NHH;
}
public String getMenuOrigin() {
return menuOrigin;
}
public void setMenuOrigin(String menuOrigin) {
this.menuOrigin = menuOrigin;
}
/**
* Metodo que inicializa los valores del cliente.
*/
private void initCustomerInfo() {
this.setSites(new ArrayList<SiteVO>());
this.setMpans(new ArrayList<MpanVO>());
List<OfferSitesVO> offerSitesAux = new ArrayList<OfferSitesVO>();
FacesMessage msg = null;
try{
log.debug("initCustomerInfo: Start");
IOffersBean offerBean = BeanInstanceLocator.getOffersBean();
this.setCustomer(offerBean.getCustomer(customerId));
this.setManagers(offerBean.getManagerList());
if (CREATE_OFFERS_OPTION.equals(menuOrigin)){
if (selectedSites!=null){
for(int i = 0; i < selectedSites.length; i++){
offerSitesAux.add(selectedSites[i]);
}
}
this.setOfferSites(offerSitesAux);
}
else{
this.setOfferSites(offerBean.getCustomerSites(customerId));
}
this.setHh_nhh_List(offerBean.getHHNHHList());
this.setAdq_ren_List(offerBean.getAdquisitionRenewList());
}catch(Exception e){
msg = new FacesMessage("ERROR "+e.getMessage());
FacesContext.getCurrentInstance().addMessage(null, msg);
log.error("ERROR 2:: "+e.getMessage());
}
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer ProductId) {
this.productId = ProductId;
}
public List<TradebookVO> getTradeBookList() {
return tradeBookList;
}
public void setTradebookList(List<TradebookVO> tradeBookList) {
this.tradeBookList = tradeBookList;
}
public List<MddMeasurementClassVO> getMeasurementClassList() {
return measurementClassList;
}
public void setMeasurementClassList(List<MddMeasurementClassVO> MeasurementClassList) {
this.measurementClassList = MeasurementClassList;
}
public Integer getProfileClassId() {
return profileClassId;
}
public void setProfileClassId(Integer ProfileClassId) {
this.profileClassId = ProfileClassId;
}
public String getMeasurementClassId() {
return measurementClassId;
}
public void setMeasurementClassId(String MeasurementClassId) {
this.measurementClassId = MeasurementClassId;
}
public Integer getCurveId() {
return curveId;
}
public void setCurveId(Integer CurveId) {
this.curveId = CurveId;
}
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public Date getOfferFromDate() {
return offerFromDate;
}
public void setOfferFromDate(Date OfferFromDate) {
this.offerFromDate = OfferFromDate;
}
public Date getOfferToDate() {
return offerToDate;
}
public void setOfferToDate(Date OfferToDate) {
this.offerToDate = OfferToDate;
}
public Integer getTradeBookId() {
return tradeBookId;
}
public void setTradeBookId(Integer tradeBookId) {
this.tradeBookId = tradeBookId;
}
public Map<String, String> getManagers() {
return managers;
}
public void setManagers(Map<String, String> managers) {
this.managers = managers;
}
public OfferSitesVO getSelectedSite() {
return selectedSite;
}
public void setSelectedSite(OfferSitesVO selectedSite) {
this.selectedSite = selectedSite;
}
public OfferSitesVO[] getSelectedSites() {
return selectedSites;
}
public List<MpanVO> getSiteMpans() {
return siteMpans;
}
public void setSiteMpans(List<MpanVO> siteMpans) {
this.siteMpans = siteMpans;
}
public String getCopcOfferSelection() {
return copcOfferSelection;
}
public void setCopcOfferSelection(String copcOfferSelection) {
this.copcOfferSelection = copcOfferSelection;
}
public String getComcOfferSelection() {
return comcOfferSelection;
}
public void setComcOfferSelection(String comcOfferSelection) {
this.comcOfferSelection = comcOfferSelection;
}
public Map<String, String> getCotOfferTypes() {
return cotOfferTypes;
}
public void setCotOfferTypes(Map<String, String> cotOfferTypes) {
this.cotOfferTypes = cotOfferTypes;
}
public String getCotOfferSelection() {
return cotOfferSelection;
}
public void setCotOfferSelection(String cotOfferSelection) {
this.cotOfferSelection = cotOfferSelection;
}
public Date getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(Date expiryDate) {
this.expiryDate = expiryDate;
}
public SelectItem[] getCotOfferList() {
return cotOfferList;
}
public void setCotOfferList(SelectItem[] cotOfferList) {
this.cotOfferList = cotOfferList;
}
private void loadProfileClass() {
FacesMessage msg = null;
try{
log.debug("ProfileClass: Start");
IOffersBean offerBean = BeanInstanceLocator.getOffersBean();
List ProfileClassLista = offerBean.getProfileClassList(offerHH_NHH);
this.setProfileClassList((ArrayList<ProfileClassVO>) ProfileClassLista);
if(ProfileClassLista == null){
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"There are not Profile_class elements",null);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
log.debug("ProfileClassLista: end");
}catch(Exception e){
msg = new FacesMessage("ERROR "+e.getMessage());
FacesContext.getCurrentInstance().addMessage(null, msg);
log.error("ERROR 2:: "+e.getMessage());
}
}
private void loadMeasurementClass() {
FacesMessage msg;
try{
log.debug("MeasurementClass: Start");
IOffersBean offerBean = BeanInstanceLocator.getOffersBean();
List MeasureClassList = offerBean.getMeasurementClassList();
this.setMeasurementClassList((ArrayList<MddMeasurementClassVO>) MeasureClassList);
if(measurementClassList == null){
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"There are not Measurement_class elements",null);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
log.debug("loadMeasurementClass: end");
}catch(Exception e){
msg = new FacesMessage("ERROR "+e.getMessage());
FacesContext.getCurrentInstance().addMessage(null, msg);
log.error("ERROR 2:: "+e.getMessage());
}
}
}
I have injected one request scoped bean into another view scoped bean
You're not allowed to inject a bean into another bean of a wider scope.
As a rule, the following abominations are not allowed :)
#RequestScoped >> #ViewScoped
#ViewScoped >>#SessionScoped
#SessionScoped >> #ApplicationScoped
EDIT (Based on your update): Injecting a property of a bean, as against injecting the bean itself, will result in a static injection. The static injection means that the value that's injected into the target is what's available as at the time of injection. As a the time the following line was executed:
#ManagedProperty(value="#{selectOfferMpans.selectedSites}")
selectedSites is null. So what you should be doing there instead is injecting the entire bean
#ManagedProperty(value="#{selectOfferMpans}")
This way, you'll have access to the current value of whatever variable you're interested in

NoSuchMethodException on eclipselink

I'm developing a javaEE project using Glassfish and EclipseLink.
ALthough, when i run my app i get the following exceptions:
Exception [EclipseLink-60] (Eclipse Persistence Services - 2.0.1.v20100213-r6600): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The method [_persistence_setjuego_vh] or [_persistence_getjuego_vh] is not defined in the object [model.ConcursosJuego].
Internal Exception: java.lang.NoSuchMethodException: model.ConcursosJuego._persistence_getjuego_vh()
i have no clue why i am getting this exception becuase the Entity "Juegos" has that methods, this is the Entity Code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
*
* #author user
*/
#Entity
#NamedQueries({
#NamedQuery(name = "Juego.findAll", query = "SELECT j FROM Juego j"),
#NamedQuery(name = "Juego.findById", query = "SELECT j FROM Juego j WHERE j.id = :id"),
#NamedQuery(name = "Juego.findByNombre", query = "SELECT j FROM Juego j WHERE j.nombre = :nombre"),
#NamedQuery(name = "Juego.findByUrl", query = "SELECT j FROM Juego j WHERE j.url = :url"),
#NamedQuery(name = "Juego.findByMultijugador", query = "SELECT j FROM Juego j WHERE j.multijugador = :multijugador"),
#NamedQuery(name = "Juego.findByTopejugadores", query = "SELECT j FROM Juego j WHERE j.topejugadores = :topejugadores"),
#NamedQuery(name = "Juego.findByEstado", query = "SELECT j FROM Juego j WHERE j.estado = :estado")})
public class Juego implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 10)
private String id;
#Size(max = 255)
private String nombre;
#Size(max = 1000)
private String url;
private BigInteger multijugador;
private BigInteger topejugadores;
#Size(max = 1)
private String estado;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "juego", fetch = FetchType.LAZY)
private List<Partida> partidaList;
#JoinColumn(name = "RANKING_ID", referencedColumnName = "ID")
#ManyToOne(optional = false, fetch = FetchType.LAZY)
private Ranking ranking;
#JoinColumn(name = "CATEGORIA_ID", referencedColumnName = "ID")
#ManyToOne(optional = false, fetch = FetchType.LAZY)
private Categoria categoria;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "juego", fetch = FetchType.LAZY)
private List<InteraccionUsuarioJuego> interaccionUsuarioJuegoList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "juego", fetch = FetchType.LAZY)
private List<ConcursosJuego> concursosJuegoList;
public Juego() {
}
public Juego(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public BigInteger getMultijugador() {
return multijugador;
}
public void setMultijugador(BigInteger multijugador) {
this.multijugador = multijugador;
}
public BigInteger getTopejugadores() {
return topejugadores;
}
public void setTopejugadores(BigInteger topejugadores) {
this.topejugadores = topejugadores;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public List<Partida> getPartidaList() {
return partidaList;
}
public void setPartidaList(List<Partida> partidaList) {
this.partidaList = partidaList;
}
public Categoria getCategoria() {
return categoria;
}
public void setCategoria(Categoria categoria) {
this.categoria = categoria;
}
public List<InteraccionUsuarioJuego> getInteraccionUsuarioJuegoList() {
return interaccionUsuarioJuegoList;
}
public void setInteraccionUsuarioJuegoList(List<InteraccionUsuarioJuego> interaccionUsuarioJuegoList) {
this.interaccionUsuarioJuegoList = interaccionUsuarioJuegoList;
}
public List<ConcursosJuego> getConcursosJuegoList() {
return concursosJuegoList;
}
public void setConcursosJuegoList(List<ConcursosJuego> concursosJuegoList) {
this.concursosJuegoList = concursosJuegoList;
}
#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 Juego)) {
return false;
}
Juego other = (Juego) 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 "model.Juego[ id=" + id + " ]";
}
public Ranking getRanking() {
return ranking;
}
public void setRanking(Ranking ranking) {
this.ranking = ranking;
}
}
this is the application.xml
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:application="http://java.sun.com/xml/ns/javaee/application_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_6.xsd" id="Application_ID" version="6">
<display-name>p_ear</display-name>
<module>
<ejb>p.jar</ejb>
</module>
<module>
<web>
<web-uri>p_web.war</web-uri>
<context-root>p_web</context-root>
</web>
</module>
</application>
i have tried eclipse link persistance and methods in other entities and it does work.
(This is the first entity that have more than 1 relation)
thanks

JSF Datamodel & JPA parent to leaves navigation. How to?

My web application is a CRUD web application based on JSF 2.0 / JPA using Java EE 5 and JDK 1.6. Running on Glassfish 3.1. The IDE is Netbeans 7.0. (I do not use EJB, nor CDI).
THE PROBLEM
What I can achieve now is perform CRUD on my entities. Which is fine. For each entity I have:
List.xhtml (LIsting all Datamodel items for that entity in datatable)
Create.xhtml (A form to create a new item)
View.xhtml (a form to view an item)
Edit.xhtml (a form to edit an item)
Structure
entities package: entities.
jpa.controllers package: JPA controllers (Javax persistence..).
jsf package: a managed bean for each entity (session Scoped).
But the main problem is parent-leaf navigation. I want my webapp to do the same thing as the Demo application Agile ScrumToys that comes along shipped with Netbeans 7.0. or the demo webapp from SpringFuse, otherwise :
E.G: When you display a list of WRITERS in a you have the last <h:column> where you put three <h:commandLink /> for editing, viewing and deleting the selected row.
What I intend to do is to add another in the same column that allows me to view a collection of child objects related to that selected row.
Hence, I want to show the list of BOOKS written by a given WRITER.
WRITER 1 ---------- * BOOK (one-to-many) relationship.
When the user clicks on the
<h:commandButton action="#{someManagedBean.showBooksForWriter}" value="#{i18n.listBooks}" /> it forwards him to the /book/List.xhtml (list of the selected WRITEr row should appear). And so on, from the book datatable, from a given row, I click on <h:commandLink action="#{someManagedBean.showReferencesForBook}" value="List of Book References"/> to get the list of references for the given book.
A given hint by #Matt was to use a method in the book managed bean:
public showBooksForWriter(Writer writer) {
// TODO: get the selected writer
// Get the list of books for the selected writer
return "/book/List"; // Outcome
}
And in the view :
<h:datatable value="#{writerController.items}" var="w">
.....
<h:column>
<h:commandButton action="#{bookController.showBooksForWriter(w}" value="Show Books For Writer"/>
</h:column>
....
</h:datatable>
But I could not figure how to (DataModel is driving mad). So if anyone could help! It would be very appreciated!
Below is my code
the WRITER entity:
package entities;
import javax.persistence.*; // other imports
#Entity
#Table(name = "WRITER")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Writer.findAll", query = "SELECT w FROM Writer w"),
#NamedQuery(name = "Writer.findByWriterid", query = "SELECT w FROM Writer w WHERE w.writerid = :writerid"),
#NamedQuery(name = "Writer.findByName", query = "SELECT w FROM Writer w WHERE w.name = :name"),
#NamedQuery(name = "Writer.findBySurname", query = "SELECT w FROM Writer w WHERE w.surname = :surname"),
#NamedQuery(name = "Writer.findByMiddlename", query = "SELECT w FROM Writer w WHERE w.middlename = :middlename"),
#NamedQuery(name = "Writer.findByIsRewarded", query = "SELECT w FROM Writer w WHERE w.isRewarded = :isRewarded")})
public class Writer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "writerid")
private Integer writerid;
#Size(max = 45)
#Column(name = "name")
private String name;
#Size(max = 45)
#Column(name = "surname")
private String surname;
#Size(max = 45)
#Column(name = "middlename")
private String middlename;
#Column(name = "isRewarded")
private Boolean isRewarded;
#ManyToMany(mappedBy = "writerList")
private List<Topic> topicList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "writer")
private List<Evaluation> evaluationList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "writer")
private List<Book> bookList;
public Writer() {
}
public Writer(Integer writerid) {
this.writerid = writerid;
}
public Integer getWriterid() {
return writerid;
}
public void setWriterid(Integer writerid) {
this.writerid = writerid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getMiddlename() {
return middlename;
}
public void setMiddlename(String middlename) {
this.middlename = middlename;
}
public Boolean getIsRewarded() {
return isRewarded;
}
public void setIsRewarded(Boolean isRewarded) {
this.isRewarded = isRewarded;
}
#XmlTransient
public List<Topic> getTopicList() {
return topicList;
}
public void setTopicList(List<Topic> topicList) {
this.topicList = topicList;
}
#XmlTransient
public List<Evaluation> getEvaluationList() {
return evaluationList;
}
public void setEvaluationList(List<Evaluation> evaluationList) {
this.evaluationList = evaluationList;
}
#XmlTransient
public List<Book> getBookList() {
return bookList;
}
public void setBookList(List<Book> bookList) {
this.bookList = bookList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (writerid != null ? writerid.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 Writer)) {
return false;
}
Writer other = (Writer) object;
if ((this.writerid == null && other.writerid != null) || (this.writerid != null && !this.writerid.equals(other.writerid))) {
return false;
}
return true;
}
#Override
public String toString() {
return getMiddlename();
}
}
The Writer MANAGED BEAN
package jsf;
import entities.Writer;
import jsf.util.JsfUtil;
import jsf.util.PaginationHelper;
import jpa.controllers.WriterJpaController;
import javax.faces.bean.ManagedBean;
// other imports here
#ManagedBean(name = "writerController")
#SessionScoped
public class WriterController implements Serializable {
#Resource
private UserTransaction utx = null;
#PersistenceUnit(unitName = "writerPU")
private EntityManagerFactory emf = null;
private Writer current;
private DataModel items = null;
private WriterJpaController jpaController = null;
private PaginationHelper pagination;
private int selectedItemIndex;
public WriterController() {
}
public Writer getSelected() {
if (current == null) {
current = new Writer();
selectedItemIndex = -1;
}
return current;
}
private WriterJpaController getJpaController() {
if (jpaController == null) {
jpaController = new WriterJpaController(utx, emf);
}
return jpaController;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getJpaController().getWriterCount();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getJpaController().findWriterEntities(getPageSize(), getPageFirstItem()));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Writer) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Writer();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getJpaController().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("WriterCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (Writer) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getJpaController().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("WriterUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (Writer) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getJpaController().destroy(current.getWriterid());
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("WriterDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getJpaController().getWriterCount();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getJpaController().findWriterEntities(1, selectedItemIndex).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(getJpaController().findWriterEntities(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(getJpaController().findWriterEntities(), true);
}
#FacesConverter(forClass = Writer.class)
public static class WriterControllerConverter implements Converter {
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
WriterController controller = (WriterController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "writerController");
return controller.getJpaController().findWriter(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Writer) {
Writer o = (Writer) object;
return getStringKey(o.getWriterid());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + WriterController.class.getName());
}
}
}
}
JSF Utility Class
package jsf.util;
import javax.faces.application.FacesMessage;
// Other imports here
public class JsfUtil {
public static SelectItem[] getSelectItems(List<?> entities, boolean selectOne) {
int size = selectOne ? entities.size() + 1 : entities.size();
SelectItem[] items = new SelectItem[size];
int i = 0;
if (selectOne) {
items[0] = new SelectItem("", "---");
i++;
}
for (Object x : entities) {
items[i++] = new SelectItem(x, x.toString());
}
return items;
}
public static void addErrorMessage(Exception ex, String defaultMsg) {
String msg = ex.getLocalizedMessage();
if (msg != null && msg.length() > 0) {
addErrorMessage(msg);
} else {
addErrorMessage(defaultMsg);
}
}
public static void addErrorMessages(List<String> messages) {
for (String message : messages) {
addErrorMessage(message);
}
}
public static void addErrorMessage(String msg) {
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);
FacesContext.getCurrentInstance().addMessage(null, facesMsg);
}
public static void addSuccessMessage(String msg) {
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg);
FacesContext.getCurrentInstance().addMessage("successInfo", facesMsg);
}
public static String getRequestParameter(String key) {
return FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(key);
}
public static Object getObjectFromRequestParameter(String requestParameterName, Converter converter, UIComponent component) {
String theId = JsfUtil.getRequestParameter(requestParameterName);
return converter.getAsObject(FacesContext.getCurrentInstance(), component, theId);
}
}
JSF Pagination helper
package jsf.util;
import javax.faces.model.DataModel;
public abstract class PaginationHelper {
private int pageSize;
private int page;
public PaginationHelper(int pageSize) {
this.pageSize = pageSize;
}
public abstract int getItemsCount();
public abstract DataModel createPageDataModel();
public int getPageFirstItem() {
return page * pageSize;
}
public int getPageLastItem() {
int i = getPageFirstItem() + pageSize - 1;
int count = getItemsCount() - 1;
if (i > count) {
i = count;
}
if (i < 0) {
i = 0;
}
return i;
}
public boolean isHasNextPage() {
return (page + 1) * pageSize + 1 <= getItemsCount();
}
public void nextPage() {
if (isHasNextPage()) {
page++;
}
}
public boolean isHasPreviousPage() {
return page > 0;
}
public void previousPage() {
if (isHasPreviousPage()) {
page--;
}
}
public int getPageSize() {
return pageSize;
}
} // END of CLASS
The JPA Controller
package jpa.controllers;
import entities.Writer;
// other imports here
public class WriterJpaController implements Serializable {
public WriterJpaController(UserTransaction utx, EntityManagerFactory emf) {
this.utx = utx;
this.emf = emf;
}
private UserTransaction utx = null;
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Writer writer) throws RollbackFailureException, Exception {
if (writer.getTopicList() == null) {
writer.setTopicList(new ArrayList<Topic>());
}
if (writer.getEvaluationList() == null) {
writer.setEvaluationList(new ArrayList<Evaluation>());
}
if (writer.getBookList() == null) {
writer.setBookList(new ArrayList<Book>());
}
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
List<Topic> attachedTopicList = new ArrayList<Topic>();
for (Topic topicListTopicToAttach : writer.getTopicList()) {
topicListTopicToAttach = em.getReference(topicListTopicToAttach.getClass(), topicListTopicToAttach.getTopicname());
attachedTopicList.add(topicListTopicToAttach);
}
writer.setTopicList(attachedTopicList);
List<Evaluation> attachedEvaluationList = new ArrayList<Evaluation>();
for (Evaluation evaluationListEvaluationToAttach : writer.getEvaluationList()) {
evaluationListEvaluationToAttach = em.getReference(evaluationListEvaluationToAttach.getClass(), evaluationListEvaluationToAttach.getEvaluationPK());
attachedEvaluationList.add(evaluationListEvaluationToAttach);
}
writer.setEvaluationList(attachedEvaluationList);
List<Book> attachedBookList = new ArrayList<Book>();
for (Book bookListBookToAttach : writer.getBookList()) {
bookListBookToAttach = em.getReference(bookListBookToAttach.getClass(), bookListBookToAttach.getBookPK());
attachedBookList.add(bookListBookToAttach);
}
writer.setBookList(attachedBookList);
em.persist(writer);
for (Topic topicListTopic : writer.getTopicList()) {
topicListTopic.getWriterList().add(writer);
topicListTopic = em.merge(topicListTopic);
}
for (Evaluation evaluationListEvaluation : writer.getEvaluationList()) {
Writer oldWriterOfEvaluationListEvaluation = evaluationListEvaluation.getWriter();
evaluationListEvaluation.setWriter(writer);
evaluationListEvaluation = em.merge(evaluationListEvaluation);
if (oldWriterOfEvaluationListEvaluation != null) {
oldWriterOfEvaluationListEvaluation.getEvaluationList().remove(evaluationListEvaluation);
oldWriterOfEvaluationListEvaluation = em.merge(oldWriterOfEvaluationListEvaluation);
}
}
for (Book bookListBook : writer.getBookList()) {
Writer oldWriterOfBookListBook = bookListBook.getWriter();
bookListBook.setWriter(writer);
bookListBook = em.merge(bookListBook);
if (oldWriterOfBookListBook != null) {
oldWriterOfBookListBook.getBookList().remove(bookListBook);
oldWriterOfBookListBook = em.merge(oldWriterOfBookListBook);
}
}
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Writer writer) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
// remainder of code goes here
}
public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
// remainder of code goes here
}
public List<Writer> findWriterEntities() {
return findWriterEntities(true, -1, -1);
}
public List<Writer> findWriterEntities(int maxResults, int firstResult) {
return findWriterEntities(false, maxResults, firstResult);
}
private List<Writer> findWriterEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Writer.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Writer findWriter(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Writer.class, id);
} finally {
em.close();
}
}
public int getWriterCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Writer> rt = cq.from(Writer.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}

Resources