conversion error setting value " for 'null converter' - jsf

I'm trying to use converter, but I'm getting this error:
conversion error setting value " for 'null converter'
I don't know how to correct this. I read some errors on stack and didn't resolve. Any help?
#FacesConverter(forClass = Plataforma.class)
public class PlataformaConverter implements Converter {
private Plataformas plataformas;
public PlataformaConverter() {
plataformas = CDIServiceLocator.getBean(Plataformas.class);
}
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
Plataforma retorno = null;
if (value != null && !"".equals(value)) {
Long id = new Long(value);
retorno = plataformas.porId(id);
}
return retorno;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value != null) {
System.out.println("aa"+((Plataforma) value).getId().toString());
return ((Plataforma) value).getId().toString();
}
return "";
}
}
Entity:
#Entity
#Table(name = "plataforma")
public class Plataforma implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String nome;
#Id
#GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#NotBlank
#Size(max = 80)
#Column(nullable = false, length = 60)
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Plataforma other = (Plataforma) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
XHTML:
<p:outputLabel value="Plataforma" for="plataforma"/>
<p:selectOneMenu id="plataforma" value="#{cadastroJogoBean.jogo.plataforma}">
<f:selectItem itemLabel="Selecione a plataforma"/>
<f:selectItems value="#{cadastroPlataformaBean.listaPlataformas}" var="plataforma"
itemValue="#{plataforma}" itemLabel="#{plataforma.nome}" />
</p:selectOneMenu>

Related

Conversion error setting value for 'null converter' [duplicate]

This question already has answers here:
Conversion Error setting value for 'null Converter' - Why do I need a Converter in JSF?
(2 answers)
Closed 7 years ago.
I'm getting this conversion error message. I'm trying to get a cliente from the selectOneMenu list, then add a bonus to him.
I implemented the converter and the equals/hashcode methods.
Can you see anything wrong?
My XHTML:
<h:body>
<h:form>
<p:panel id="panel" header="Cadastro de bônus">
<p:panelGrid columns="2">
<p:outputLabel value="Cliente: " />
<p:selectOneMenu value="#{clienteBean.cliente}">
<f:selectItem itemLabel="--Selecione um cliente--" />
<f:selectItems value="#{clienteBean.selectClientes}" />
</p:selectOneMenu>
<p:outputLabel value="Informe o valor da venda:" for="valor_venda" />
<p:inputText id="valor_venda"
value="#{bonusBean.bonus.valor_venda}" />
<h:commandButton value="Próximo" action="#{bonusBean.gravar}" />
</p:panelGrid>
</p:panel>
</h:form>
</h:body>
</ui:define>
My DAO:
public class DAOCliente {
public EntityManager getEntityManager() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("cliente");
EntityManager entityManager = factory.createEntityManager();
return entityManager;
}
public void adiciona (Cliente cliente){
EntityManager entityManager = getEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(cliente);
entityManager.getTransaction().commit();
entityManager.close();
}
public void excluir(Cliente cliente)throws Exception{
EntityManager entityManager = getEntityManager();
try {
entityManager.getTransaction().begin();
cliente = entityManager.merge(cliente);
entityManager.remove(cliente);
entityManager.getTransaction().commit();
} finally {
entityManager.close();
}
}
public Cliente consultar (Long id){
Cliente cliente = new Cliente();
EntityManager entityManager = getEntityManager();
try {
entityManager.getTransaction().begin();
cliente = entityManager.find(Cliente.class, id);
entityManager.getTransaction().commit();
}
catch (Exception e) {
entityManager.getTransaction().rollback();
}
finally {
entityManager.close();
}
return cliente;
}
#SuppressWarnings("unchecked")
public List<Cliente> listarTodosClientes() throws Exception{
EntityManager entityManager = getEntityManager();
List<Cliente> lista = null;
try {
Query query = entityManager.createQuery("SELECT c FROM Cliente c");
lista = query.getResultList();
for (Cliente cliente : lista) {
System.out.println("Nome: " + cliente.getNome());
System.out.println("Fone Residencia: " + cliente.getFone_residencia());
System.out.println("Fone Celular: " + cliente.getFone_celular());
System.out.println("Perfil FB: " + cliente.getPerfil_facebook());
System.out.println("------------------------------------");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
entityManager.close();
}
return lista;
}
}
My converter:
#FacesConverter(forClass = ClienteBean.class)
public class ConverterCliente implements Converter {
#Override
public Object getAsObject(FacesContext ctx, UIComponent component, String value) {
if(value!=null && value.trim().length()>0){
Long id = Long.valueOf(value);
DAOCliente dao = new DAOCliente();
return dao.consultar(id);
}
return null;
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
if(value!=null){
Cliente cliente = (Cliente) value;
return cliente.getId().toString();
}
return null;
}
}
My Managed Bean:
#ManagedBean
public class ClienteBean {
private Cliente cliente;
List<Cliente> clientes;
List<SelectItem> selectClientes;
DAOCliente dao = new DAOCliente();
public List<SelectItem> getSelectClientes() throws Exception {
if(selectClientes==null){
selectClientes = new ArrayList<SelectItem>();
clientes = dao.listarTodosClientes();
if(clientes!=null && !clientes.isEmpty()){
SelectItem item;
for(Cliente lista : clientes){
item = new SelectItem(lista, lista.getNome());
selectClientes.add(item);
}
}
}
return selectClientes;
}
public List<Cliente> getClientes() throws Exception{
if(clientes == null){
clientes = dao.listarTodosClientes();
}
return clientes;
}
public Cliente getCliente() {
return cliente;
}
public void gravar() {
dao.adiciona(cliente);
this.cliente = new Cliente();
}
public void excluir(Cliente cliente) throws Exception{
dao.excluir(cliente);
}
public void setClientes(List<Cliente> clientes) {
this.clientes = clientes;
}
}
My Cliente class:
public class Cliente {
#Id #GeneratedValue
private Long id;
private String nome;
private String fone_residencia;
private String fone_celular;
private String perfil_facebook;
#OneToMany(mappedBy = "cliente", fetch = FetchType.EAGER, targetEntity = Bonus.class, cascade = CascadeType.ALL)
private List<Bonus> bonus;
public List<Bonus> getBonus() {
return bonus;
}
public void setBonus(List<Bonus> bonus) {
this.bonus = bonus;
}
public String getPerfil_facebook() {
return perfil_facebook;
}
public void setPerfil_facebook(String perfil_facebook) {
this.perfil_facebook = perfil_facebook;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getFone_residencia() {
return fone_residencia;
}
public void setFone_residencia(String fone_residencia) {
this.fone_residencia = fone_residencia;
}
public String getFone_celular() {
return fone_celular;
}
public void setFone_celular(String fone_celular) {
this.fone_celular = fone_celular;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((bonus == null) ? 0 : bonus.hashCode());
result = prime * result
+ ((fone_celular == null) ? 0 : fone_celular.hashCode());
result = prime * result
+ ((fone_residencia == null) ? 0 : fone_residencia.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
result = prime * result
+ ((perfil_facebook == null) ? 0 : perfil_facebook.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Cliente other = (Cliente) obj;
if (bonus == null) {
if (other.bonus != null)
return false;
} else if (!bonus.equals(other.bonus))
return false;
if (fone_celular == null) {
if (other.fone_celular != null)
return false;
} else if (!fone_celular.equals(other.fone_celular))
return false;
if (fone_residencia == null) {
if (other.fone_residencia != null)
return false;
} else if (!fone_residencia.equals(other.fone_residencia))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (nome == null) {
if (other.nome != null)
return false;
} else if (!nome.equals(other.nome))
return false;
if (perfil_facebook == null) {
if (other.perfil_facebook != null)
return false;
} else if (!perfil_facebook.equals(other.perfil_facebook))
return false;
return true;
}
#Override
public String toString() {
return "Cliente [id=" + id + ", nome=" + nome + ", fone_residencia="
+ fone_residencia + ", fone_celular=" + fone_celular
+ ", perfil_facebook=" + perfil_facebook + ", bonus=" + bonus
+ "]";
}
}
You should mention the used converter class in the concerned tag to enable conversion :
<p:selectOneMenu value="#{clienteBean.cliente}" converter="converterCliente">
...
</p:selectOneMenu>

PickList PrimeFaces not working

I try to use the pickList component of Primefaces. My converter does not work properly and I don't know why.
This is my ManagedBean:
#ManagedBean(name = "comMB")
#SessionScoped
public class TeamCompetitionBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private DualListModel<Team> teams;
List<Team> source;
List<Team> source1;
List<Team> target;
#ManagedProperty("#{team}")
private TeamServiceI teamService;
List<String> teamNameList ;
// public TeamCompetitionBean() {
public DualListModel<Team> getTeams() {
// Players
teamNameList = new ArrayList<String>();
source = new ArrayList<Team>();
target = new ArrayList<Team>();
source.addAll(getTeamService().getTeam());
teams = new DualListModel<Team>(source, target);
return teams;
}
public void setTeams(DualListModel<Team> teams) {
this.teams = teams;
}
public void onTransfer(TransferEvent event) {
StringBuilder builder = new StringBuilder();
for (Object item : event.getItems()) {
builder.append(((Team) item).getTeamName()).append("<br />");
}
FacesMessage msg = new FacesMessage();
msg.setSeverity(FacesMessage.SEVERITY_INFO);
msg.setSummary("Items Transferred");
msg.setDetail(builder.toString());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public TeamServiceI getTeamService() {
return teamService;
}
public void setTeamService(TeamServiceI teamService) {
this.teamService = teamService;
}
public List<Team> getSource() {
return source;
}
public void setSource(List<Team> source) {
this.source = source;
}
public List<Team> getTarget() {
return target;
}
public void setTarget(List<Team> target) {
this.target = target;
}
public void afficher(){
System.out.println(target);
System.out.println(source);
}
}
and this is my entity class that I would like to load in my pickList:
#Entity
#Table(name = "team", catalog = "competition_manager")
public class Team implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer idTeam;
private Stadium stadium;
private League league;
private String teamName;
// getters and setters
#Override
public String toString() {
return teamName.toString();
}
#Override
public boolean equals(Object obj) {
if (!(obj instanceof Team)) {
return false;
}
Team f = (Team) obj;
return (this.idTeam == f.getIdTeam());
}
Now, this is my custom Converter:
#FacesConverter(forClass = Team.class, value = "teamConverter")
public class TeamConverter implements Converter {
Team team;
public Object getAsObject(FacesContext facesContext, UIComponent component,
String value) {
System.out.println("hello object");
if (value == null || value.length() == 0) {
return null;
}
ApplicationContext ctx = FacesContextUtils
.getWebApplicationContext(FacesContext.getCurrentInstance());
TeamBean controller = (TeamBean) ctx.getBean("teamMB");
List<Team> liststagiaire = controller.getTeamList();
for (int i = 0; i < liststagiaire.size(); i++)
{
team = liststagiaire.get(i);
if (team.getIdTeam() == getKey(value)) {
break;
}
}
return team;
}
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) {
System.out.println("hello string");
if (object == null) {
System.out.println("hello string null");
return null;
}
if (object instanceof Team) {
System.out.println("hello string intance of");
Team o = (Team) object;
String i = getStringKey(o.getIdTeam());
return i;
} else {
System.out.println("hello throw");
throw new IllegalArgumentException("object " + object
+ " is of type " + object.getClass().getName()
+ "; expected type: " + Team.class.getName());
}
}
}
And finally this is my XHTML page:
<p:pickList id="teamPickList" value="#{comMB.teams}" var="team"
itemValue="#{team}" itemLabel="#{team}" converter="teamConverter">
</p:pickList>
Your problem is comming from this line (in your class TeamConverter) :
if (team.getIdTeam() == getKey(value)) {
You can't compare Integer objects like that, because doing like this you are comparing reference. You should replace this line by
if (team.getIdTeam().intValue() == getKey(value).intValue()) {
You have the same problem in your class Team :
return (this.idTeam == f.getIdTeam());
should be replaced by :
return (this.idTeam.intValue() == f.getIdTeam().intValue());
Not related :
You don't need to use getKey and getStringKey, you could replace them simply like this :
getKey(value) // this
Integer.valueOf(value) // by this
and
getStringKey(o.getIdTeam()) // this
o.getIdTeam().toString() // by this
Also you should replace itemLabel="#{team}" by itemLabel="#{team.teamName}" in your view.

JSF: No validator could be found for type when adding a converter and a validator to a p:selectOneMenu

I'm currently encountering the problem specified above when trying to add a converter and a validator to a single field. I know how these 2 works because I've used them before, but this is the first time I've tried both of them on a single field. Here are my codes:
<p:selectOneMenu id="bussProgram"
value="#{signupWizardBean.subscription.businessProgram}">
<f:converter binding="#{membershipProgramConverter}"></f:converter>
<f:validator binding="#{dropdownValidator}"></f:validator>
<f:selectItems value="#{signupWizardBean.membershipPrograms}"
var="plan" itemValue="#{plan}"
itemLabel="#{plan.description}" />
</p:selectOneMenu>
Converter
#Named
#ApplicationScoped
public class MembershipProgramConverter implements Converter {
#PersistenceContext
private transient EntityManager em;
#Inject
private Logger log;
#Override
public Object getAsObject(FacesContext ctx, UIComponent component,
String value) {
if (StringUtils.isBlank(value) || value.equals("0"))
return null;
return em.find(MembershipProgram.class, new Long(value));
}
#Override
public String getAsString(FacesContext fc, UIComponent uic, Object o) {
MembershipProgram mp = (MembershipProgram) value;
return mp.getId() != null ? String.valueOf(mp.getId()) : null;
}
}
Validator:
#Named
#ApplicationScoped
public class DropdownValidator implements Validator, Serializable {
private static final long serialVersionUID = -456545939475878299L;
#Inject
private ResourceBundle bundle;
#Inject
private FacesContext facesContext;
#Inject
private Logger log;
#Override
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
log.debug("[dropship-web] validating value={}", value);
if (value == null) {
FacesMessage msg = new FacesMessage(
bundle.getString("error.requiredField"),
bundle.getString("error.requiredField"));
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
facesContext.addMessage("promoCode", msg);
throw new ValidatorException(msg);
}
}
}
Entity Class:
#Entity
#Table(name = "CRM_MEMBERSHIP_PROGRAMS", uniqueConstraints = #UniqueConstraint(columnNames = { "code" }))
#SequenceGenerator(name = "ID_GENERATOR", sequenceName = "CRM_MEMBERSHIP_PROGRAM_SEQ")
public class MembershipProgram extends BaseEntity {
private static final long serialVersionUID = -7796298586810386239L;
#Size(max = 25)
#Column(name = "CODE", nullable = false)
private String code;
#Size(max = 100)
#Column(name = "DESCRIPTION", nullable = true)
private String description;
public MembershipProgram() {
}
public MembershipProgram(long id, String description) {
setId(id);
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
#Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((code == null) ? 0 : code.hashCode());
result = prime * result
+ ((description == null) ? 0 : description.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
MembershipProgram other = (MembershipProgram) obj;
if (code == null) {
if (other.code != null)
return false;
} else if (!code.equals(other.code))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
return true;
}
}
Note that on debug: both the MembershipProgramConverter.getAsObject/getAsString, DropdownValidator.validate methods are called.
I also found out that with or without selected item from the dropdown list, I'm encountering:
.validation.UnexpectedTypeException: HV000030: No validator could be found for type: com.czetsuya.models.membership.MembershipProgram.
javax.validation.UnexpectedTypeException: HV000030: No validator could be found for type: com.czetsuya.models.membership.MembershipProgram.
Finally I was able to figure out the problem, I've added #Size annotation on the target entity, just removed the #Size:
#Size(max = 25)
#OneToOne(optional = false)
#JoinColumn(name = "BUSINESS_PROGRAM", nullable = false)
private MembershipProgram businessProgram;
When I removed the #Size, the problem was solved but I have encountered a new one, on submit it the form always throw:
Validation Error: Value is not valid
To fixed the Value is not valid, make sure that you have properly implemented Model.equals method. My fault was that I rely on eclipse generate hashcode and equals feature, I failed to notice that it calls the equals method from my BaseEntity.

How can we enable many to many relationship through a JSF page using Netbeans?

Used a simple InnoDB MySQL database (many to many relationship between WRITER and FORUM, and a join table named writer_forum) in Netbeans 7.1 and created a Java EE 6 web application running under Glassfish 3.1 Open Source Edition. No Other frameworks are being used except JSF 2.0
Generated Entities from Database (using EclipseLink (JPA 2.0) and everything seems fine, the code in the entities is correct as far as I can tell.
Generated JSF pages from Entities (the IDE generates EJB Session beans, Managed Beans and JSF pages using facelets .xhtml).
ALl relationships are supported except MANY TO MANY.
Does anyone had the same experience and managed to enable Many to Many relationship support?
package entities;
#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.findByField", query = "SELECT w FROM Writer w WHERE w.field = :field")})
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;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "name")
private String name;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "surname")
private String surname;
#Size(max = 45)
#Column(name = "field")
private String field;
#ManyToMany(mappedBy = "writerCollection")
private Collection<Forum> forumCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "writer")
private Collection<Book> bookCollection;
public Writer() {
}
public Writer(Integer writerid) {
this.writerid = writerid;
}
public Writer(Integer writerid, String name, String surname) {
this.writerid = writerid;
this.name = name;
this.surname = surname;
}
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 getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
#XmlTransient
public Collection<Forum> getForumCollection() {
return forumCollection;
}
public void setForumCollection(Collection<Forum> forumCollection) {
this.forumCollection = forumCollection;
}
#XmlTransient
public Collection<Book> getBookCollection() {
return bookCollection;
}
public void setBookCollection(Collection<Book> bookCollection) {
this.bookCollection = bookCollection;
}
#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 name + " | " + writerid;
}
}
-------- FORUM JPA entity
#Entity
#Table(name = "forum")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Forum.findAll", query = "SELECT f FROM Forum f"),
#NamedQuery(name = "Forum.findByForumid", query = "SELECT f FROM Forum f WHERE f.forumid = :forumid"),
#NamedQuery(name = "Forum.findByLabel", query = "SELECT f FROM Forum f WHERE f.label = :label")})
public class Forum implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "forumid")
private Integer forumid;
#Size(max = 45)
#Column(name = "label")
private String label;
#JoinTable(name = "forum_writer", joinColumns = {
#JoinColumn(name = "forum_forumid", referencedColumnName = "forumid")}, inverseJoinColumns = {
#JoinColumn(name = "writer_writerid", referencedColumnName = "writerid")})
#ManyToMany
private Collection<Writer> writerCollection;
public Forum() {
}
public Forum(Integer forumid) {
this.forumid = forumid;
}
public Integer getForumid() {
return forumid;
}
public void setForumid(Integer forumid) {
this.forumid = forumid;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
#XmlTransient
public Collection<Writer> getWriterCollection() {
return writerCollection;
}
public void setWriterCollection(Collection<Writer> writerCollection) {
this.writerCollection = writerCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (forumid != null ? forumid.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 Forum)) {
return false;
}
Forum other = (Forum) object;
if ((this.forumid == null && other.forumid != null) || (this.forumid != null && !this.forumid.equals(other.forumid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.Forum[ forumid=" + forumid + " ]";
}
}
Asbtract Facade
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();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
Forum Facade
#Stateless
public class ForumFacade extends AbstractFacade<Forum> {
#PersistenceContext(unitName = "writerPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public ForumFacade() {
super(Forum.class);
}
}
------------- Managed Bean
#ManagedBean(name = "writerController")
#SessionScoped
public class WriterController implements Serializable {
private Writer current;
private DataModel items = null;
#EJB
private session.WriterFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public WriterController() {
}
public Writer getSelected() {
if (current == null) {
current = new Writer();
selectedItemIndex = -1;
}
return current;
}
private WriterFacade 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 = (Writer) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Writer();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getFacade().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 {
getFacade().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();
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("WriterDeleted"));
} 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);
}
#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.ejbFacade.find(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());
}
}
}
}
---------- XTMLCreate PAGE for WRITER----
**
<?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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<ui:composition template="/template.xhtml">
<ui:define name="title">
<h:outputText value="#{bundle.CreateWriterTitle}"></h:outputText>
</ui:define>
<ui:define name="body">
<h:panelGroup id="messagePanel" layout="block">
<h:messages errorStyle="color: red" infoStyle="color: green" layout="table"/>
</h:panelGroup>
<h:form>
<h:panelGrid columns="2">
<h:outputLabel value="#{bundle.CreateWriterLabel_writerid}" for="writerid" />
<h:inputText id="writerid" value="#{writerController.selected.writerid}" title="#{bundle.CreateWriterTitle_writerid}" required="true" requiredMessage="#{bundle.CreateWriterRequiredMessage_writerid}"/>
<h:outputLabel value="#{bundle.CreateWriterLabel_name}" for="name" />
<h:inputText id="name" value="#{writerController.selected.name}" title="#{bundle.CreateWriterTitle_name}" required="true" requiredMessage="#{bundle.CreateWriterRequiredMessage_name}"/>
<h:outputLabel value="#{bundle.CreateWriterLabel_surname}" for="surname" />
<h:inputText id="surname" value="#{writerController.selected.surname}" title="#{bundle.CreateWriterTitle_surname}" required="true" requiredMessage="#{bundle.CreateWriterRequiredMessage_surname}"/>
<h:outputLabel value="#{bundle.CreateWriterLabel_field}" for="field" />
<h:inputText id="field" value="#{writerController.selected.field}" title="#{bundle.CreateWriterTitle_field}" />
</h:panelGrid>
<br />
<h:commandLink action="#{writerController.create}" value="#{bundle.CreateWriterSaveLink}" />
<br />
<br />
<h:commandLink action="#{writerController.prepareList}" value="#{bundle.CreateWriterShowAllLink}" immediate="true"/>
<br />
<br />
<h:commandLink value="#{bundle.CreateWriterIndexLink}" action="/index" immediate="true" />
</h:form>
</ui:define>
</ui:composition>
</html>
**
I am not 100% sure but I think, you may not retrieving any results beacuse of #XMLTransiet annotation above the Serie.class method;
#XmlTransient
public Collection<Writer> getWriterCollection() {
return writerCollection;
}
I would also like to review these documents https://docs.oracle.com/javaee/6/api/javax/xml/bind/annotation/XmlTransient.html

selectOneMenu in dataTable, default value not getting set properly

When I place a selectOneMenu within a dataTable, it does not display the correct default value in the selectOneMenu. The datatable is bound to a list of POJO's. The POJO entity Badge references a POJO entity we will call Facility. This Facility should be the selected value of the selectOneMenu in the row (the row being each Badge).
The following is my simple example of a table:
<h:dataTable id="examp" value="#{managedBean.badges}" var="badge">
<h:column rowHeader="rowie">
<h:selectOneMenu value="#{badge.facility}" id="col1">
<f:converter converterId="facilityConverter" />
<f:selectItems value="#{managedBean.facilities}"
/>
</h:selectOneMenu>
</h:column>
</h:dataTable>
The selectItems are a List of SelectItem objects that are created at PostConstruct. These are within my managedbean that is in ViewScope.
public class ListBadges extends BaseBean {
private List<Badge> badges = new ArrayList<Badge>();
private List<SelectItem> facilities = new ArrayList<SelectItem>();
public ListBadges() {
getBadgesFromDatabase(true);
}
#PostConstruct
public void init() {
if (facilities.size() <= 0) {
try {
List<Facility> facilityBeans = FacilityHelper.getFacilities();
for (Facility fac : facilityBeans) {
facilities.add(new SelectItem(fac, fac.getFacilityName()));
}
} catch (tException e) {
log.error("ListBadges.init(): " + e.getMessage());
e.printStackTrace();
}
}
}
public void getBadgesFromDatabase(boolean forceRefresh) {
if (forceRefresh || badges == null || badges.isEmpty())
badges = BadgeHelper.getBadgeList();
}
///
/// Bean Properties
///
public List<Badge> getBadges() {
return badges;
}
public void setBadges(List<Badge> badges) {
this.badges = badges;
}
public List<SelectItem> getFacilities() {
return facilities;
}
public void setFacilities(List<SelectItem> facilities) {
this.facilities = facilities;
}
Stepping through the code I confirm that all of the data is correct. In my converter, I verified that the arguments passed to getAsString is correct, so it should have identified the correct item.
#FacesConverter("facilityConverter")
public class FacilityConverter implements Converter {
#Override
public Object getAsObject(FacesContext context, UIComponent component, String from) {
try {
ELContext elContext = FacesContext.getCurrentInstance().getELContext();
ListBadges neededBean =
(ListBadges) context.getApplication().getELResolver().getValue(elContext, null, "managedBean");
long id = Long.parseLong(from);
for (SelectItem sItem : neededBean.getFacilities()) {
Facility facility = (Facility)sItem.getValue();
if (facility.getFacilityId() == id)
return facility;
}
} catch (Exception e) {
}
return null;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
try {
Facility facility = (Facility)value;
return facility.getFacilityId() + "";
} catch (Exception e) {
}
return null;
}
}
Here is the Facility class which has equals and hashCode implemented:
public class Facility implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private long facilityId;
private String facilityName;
private String address1;
private String address2;
private String city;
private String state;
private String postalCode;
private String url;
private String phone;
private String siteManager;
public Facility() {
}
public Facility(String facilityName) {
this.facilityName = facilityName;
}
public Facility(String facilityName,
String address1, String address2, String city, String state,
String postalCode, String url, String phone, String siteManager) {
this.facilityName = facilityName;
this.address1 = address1;
this.address2 = address2;
this.city = city;
this.state = state;
this.postalCode = postalCode;
this.url = url;
this.phone = phone;
this.siteManager = siteManager;
}
public long getFacilityId() {
return this.facilityId;
}
public void setFacilityId(long facilityId) {
this.facilityId = facilityId;
}
public String getFacilityName() {
return this.facilityName;
}
public void setFacilityName(String facilityName) {
this.facilityName = facilityName;
}
public String getAddress1() {
return this.address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return this.address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getPostalCode() {
return this.postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getSiteManager() {
return siteManager;
}
public void setSiteManager(String siteManager) {
this.siteManager = siteManager;
}
#Override
public boolean equals(Object o) {
if (!(o instanceof Facility) || (o == null))
return false;
if (o == this)
return true;
Facility obj = (Facility)o;
return obj.getFacilityId() == this.getFacilityId();
}
#Override
public int hashCode() {
return (new Long(this.getFacilityId()).hashCode()) ^
((this.getAddress1() == null) ? 0 : this.getAddress1().hashCode()) ^
((this.getAddress2() == null) ? 0 : this.getAddress2().hashCode()) ^
((this.getCity() == null) ? 0 : this.getCity().hashCode()) ^
((this.getFacilityName() == null) ? 0 : this.getFacilityName().hashCode()) ^
((this.getPhone() == null) ? 0 : this.getPhone().hashCode()) ^
((this.getPostalCode() == null) ? 0 : this.getPostalCode().hashCode()) ^
((this.getSiteManager() == null) ? 0 : this.getSiteManager().hashCode()) ^
((this.getUrl() == null) ? 0 : this.getUrl().hashCode());
}
}
I would greatly appreciate any feedback.
I found the problem and it is nothing to do with JSF.
Eclipse was loading an older version of the Facility bean class that had a programmatic mistake in its equals method. Even after fully cleaning, republishing, cleaning the working directory, restarting the web server, and restarting Eclipse this old class was still getting loaded. I restarted my computer and finally the correct class was being loaded and this problem went away.
Thanks for looking at this BalusC. Without this blog article you wrote I would be completely lost! http://balusc.blogspot.com/2007/09/objects-in-hselectonemenu.html

Resources