tags:

views:

238

answers:

1

i get new Error with converter

javax.faces.component.UpdateModelException: java.lang.IllegalArgumentException: Cannot convert 5 of type class java.lang.Integer to class com.jpa.entity.Groups
    at javax.faces.component.UIInput.updateModel(UIInput.java:839)
    at javax.faces.component.UIInput.processUpdates(UIInput.java:722)
    at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1108)
    at javax.faces.component.UIForm.processUpdates(UIForm.java:270)
    at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1108)
    at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1108)
    at javax.faces.component.UIViewRoot.processUpdates(UIViewRoot.java:1239)
    at com.sun.faces.lifecycle.UpdateModelValuesPhase.execute(UpdateModelValuesPhase.java:78)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
    at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
    at java.lang.Thread.run(Thread.java:619)
Caused by: java.lang.IllegalArgumentException: Cannot convert 5 of type class java.lang.Integer to class com.jpa.entity.Groups
    at com.sun.el.lang.ELSupport.coerceToType(ELSupport.java:397)
    at com.sun.el.parser.AstValue.setValue(AstValue.java:194)
    at com.sun.el.ValueExpressionImpl.setValue(ValueExpressionImpl.java:286)
    at com.sun.faces.facelets.el.TagValueExpression.setValue(TagValueExpression.java:124)
    at javax.faces.component.UIInput.updateModel(UIInput.java:805)

5 is value of GroupsID

i was read tutorial at http://balusc.blogspot.com/2007/09/objects-in-hselectonemenu.html and http://www.javabeat.net/articles/15-introduction-to-jsf-core-tags-library-2.html but how can i convert it? because equals and hashcode method i was override in class Groups

Groups Class

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.jpa.entity;

import java.io.Serializable;
import java.util.List;
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;

/**
 *
 * @author KencyWindy
 */
@Entity
@Table(name = "groups")
@NamedQueries({
    @NamedQuery(name = "Groups.findAll", query = "SELECT g FROM Groups g"),
    @NamedQuery(name = "Groups.findByGroupid", query = "SELECT g FROM Groups g WHERE g.groupid = :groupid"),
    @NamedQuery(name = "Groups.findByGroupname", query = "SELECT g FROM Groups g WHERE g.groupname = :groupname")})
public class Groups implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "groupid")
    private Integer groupid;
    @Basic(optional = false)
    @Column(name = "groupname")
    private String groupname;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "groups")
    private List<TblUser> tblUserList;

    public Groups() {
    }

    public Groups(Integer groupid) {
        this.groupid = groupid;
    }

    public Groups(Integer groupid, String groupname) {
        this.groupid = groupid;
        this.groupname = groupname;
    }

    public Integer getGroupid() {
        return groupid;
    }

    public void setGroupid(Integer groupid) {
        this.groupid = groupid;
    }

    public String getGroupname() {
        return groupname;
    }

    public void setGroupname(String groupname) {
        this.groupname = groupname;
    }

    public List<TblUser> getTblUserList() {
        return tblUserList;
    }

    public void setTblUserList(List<TblUser> tblUserList) {
        this.tblUserList = tblUserList;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (groupid != null ? groupid.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 Groups)) {
            return false;
        }
        Groups other = (Groups) object;
        if ((this.groupid == null && other.groupid != null) || (this.groupid != null && !this.groupid.equals(other.groupid))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.jpa.entity.Groups[groupid=" + groupid + "]";
    }

}

TblUser Class

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.jpa.entity;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 *
 * @author KencyWindy
 */
@Entity
@Table(name = "tbl_user")
@NamedQueries({
    @NamedQuery(name = "TblUser.findAll", query = "SELECT t FROM TblUser t"),
    @NamedQuery(name = "TblUser.findByUserid", query = "SELECT t FROM TblUser t WHERE t.userid = :userid"),
    @NamedQuery(name = "TblUser.findByUsername", query = "SELECT t FROM TblUser t WHERE t.username = :username"),
    @NamedQuery(name = "TblUser.findByPassword", query = "SELECT t FROM TblUser t WHERE t.password = :password"),
    @NamedQuery(name = "TblUser.findByDob", query = "SELECT t FROM TblUser t WHERE t.dob = :dob"),
    @NamedQuery(name = "TblUser.findByAddress", query = "SELECT t FROM TblUser t WHERE t.address = :address")})
public class TblUser implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "userid")
    private Integer userid;
    @Basic(optional = false)
    @Column(name = "username")
    private String username;
    @Basic(optional = false)
    @Column(name = "password")
    private String password;
    @Basic(optional = false)
    @Column(name = "dob")
    @Temporal(TemporalType.TIMESTAMP)
    private Date dob;
    @Basic(optional = false)
    @Column(name = "address")
    private String address;
    @JoinColumn(name = "igroup", referencedColumnName = "groupid")
    @ManyToOne(optional = false)
    private Groups groups;

    public TblUser() {
    }

    public TblUser(Integer userid) {
        this.userid = userid;
    }

    public TblUser(Integer userid, String username, String password, Date dob, String address) {
        this.userid = userid;
        this.username = username;
        this.password = password;
        this.dob = dob;
        this.address = address;
    }

    public Integer getUserid() {
        return userid;
    }

    public void setUserid(Integer userid) {
        this.userid = userid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Date getDob() {
        return dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Groups getGroups() {
        return groups;
    }

    public void setGroups(Groups groups) {
        this.groups = groups;
    }

    public Integer getGroupID(){
        return this.groups.getGroupid();
    }

    public void setGroupID(Integer iGroup){
        this.groups = new Groups(iGroup);
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (userid != null ? userid.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 TblUser)) {
            return false;
        }
        TblUser other = (TblUser) object;
        if ((this.userid == null && other.userid != null) || (this.userid != null && !this.userid.equals(other.userid))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.jpa.entity.TblUser[userid=" + userid + "]";
    }

}

method Grouplist

>  public javax.faces.model.SelectItem[]
> getGroupList(){
>         SelectItem[] options = null;
> 
>             List<Groups> iGroup = userBean.retrieveAllGroup();
>             if(iGroup != null && iGroup.size() > 0){
>                 options = new SelectItem[iGroup.size()];
>                 int i = 0 ;
>                 for(Groups groups : iGroup){
>                     options[i++] = new SelectItem(groups.getGroupid(),
> groups.getGroupname());
>                 }
>             }
> 
>         return options;
>     }

JSF file

<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html"
      >
    <h:head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>TODO supply a title</title>

    </h:head>
    <h:body>
        <f:view>
            <h:form>
                <h1><h:outputText value="Create/Edit"/></h1>
                <h:panelGrid columns="2">
                     <h:outputLabel value="Username" for="username" />
                    <h:inputText id="username" value="#{userController.user.username}" title="Username" required="true" requiredMessage="The Username field is required."/>
                    <h:outputLabel value="Password:" for="password" />
                    <h:inputText id="password" value="#{userController.user.password}" title="Password" required="true" requiredMessage="The Password field is required."/>
                    <h:outputLabel value="Dob:" for="dob" />
                    <h:inputText id="dob" value="#{userController.user.dob}" title="Dob" required="true" requiredMessage="The Dob field is required.">
                        <f:convertDateTime pattern="MM/dd/yyyy" />
                    </h:inputText>
                    <h:outputLabel value="Address:" for="address" />
                    <h:inputText id="address" value="#{userController.user.address}" title="Address" required="true" requiredMessage="The Address field is required."/>
                    <h:inputHidden/>
                    <h:selectOneMenu id="igroup" value="#{userController.user.groups}" title="Igroup" required="true" requiredMessage="The Igroup field is required.">
                        <!-- TODO: update below reference to list of available items-->
                        <f:selectItems value="#{userController.groupList}"/>
                        <f:converter converterId="javax.faces.Integer"/>
                    </h:selectOneMenu>
                </h:panelGrid>
                <h:commandButton value="Ok" action="#{userController.addUser}"/>
            </h:form>
        </f:view>


    </h:body>
</html>
A: 

I have no idea how your JSF code look like, but I suspect that you're using

<h:selectOneMenu value="#{bean.group}">

instead of

<h:selectOneMenu value="#{bean.groupId}">

Your SelectItem[] contains Integer groupId as item values. The value attribute of the h:selectOneMenu must then match this type. The exception message is telling exactly that. The value is submitted as an Integer, but the bean is expecting a Group.

BalusC
Hi BalusC user.Groups it mean groups Object and GroupID it means Groups ID with integer Type, in JSF file i was get error with <h:selectOneMenu value = #{bean.user.groups} /> when i change selectOneMenu value to bean.groupID or bean.user.groupID it throws Nullpointer Exception
Kency
Read the stacktrace and fix the code accordingly.
BalusC
i create new instance of groups in controller private Groups groups ; and in constructor public userController(){ groups = new Groups() } and set set/get methods for groups variable . and JSF in h:selectOneMenu i change value to #{bean.groups} it work well but when i submit form , the same error occur! what's happen with it? Stacktrace the same error i was post above
Kency
The exception is telling that you're submitting `Integer`, but the bean property expects `Group`. You need to either submit `Group` instead or to change the property to take `Integer`. As I stated in my answer.
BalusC
An alternative is to create a converter which converts between `Integer` and `Group`, but then you'll have to make changes in how you populate `f:selectItems`. A JSF 2.0 example can be found in [this answer](http://stackoverflow.com/questions/3711572/jsf-select-items-from-subclass/3711621#3711621).
BalusC
Hi BalusC i following your supported link but new error occur when i Cast Groups for value.getGroupID (integer type) in a getAsString Method ---- return String.valueOf(((Groups)value).getGroupid()); <== this line occour ClassCastException . in JSF page i was indicate name of class Converter is GroupIDConverter and mapped in to face-config.xml file. Once again how to be solved this problem? Thank you before!
Kency
this not cast Groups for integer ?? what's happen?
Kency
Then value is not a `Groups` at all. You need to change `SelectItem` values to be `Groups` as well. Your major problem is just that the submitted type and the expected type are both **different**. In your original problem, you're attempting to submit an `Integer` value into a `Groups` bean property. You need to align out the value types. This be done in 2 ways: submit `Integer` value into an `Integer` bean property (e.g. `#{bean.groupsId}` as in answer). OR submit a `Groups` value into an `Groups` bean property (and use a converter because `Groups` is a custom type and not understood by EL).
BalusC
i was change it into Groups type and used converter class and i was created one method call with name findGroupID with below - public Groups findByGroupId(Integer groups){ try { return em.find(Groups.class, groups); } finally { em.close(); } } and in getObjet Method in Converter class i throw ConverterException with message Cannot convert %s to Groups", value. when i enter info into form and submit, it throw ConverterException , i don't know why it throw Exception??
Kency
Sorry Kency, I give up. You seem not to understand the importance of typing. I'll give only one more hint: based on the code as you've posted in the question, the above answer still applies. You need to replace `<h:selectOneMenu value="#{bean.groups}">` by `<h:selectOneMenu value="#{bean.groupsId}">` (which takes an `Integer`). That's all.
BalusC
BalusC i know your comment but when i change bean.groupsID it throws Target null exception, now i try to fix it, anyway thank you for support , :D
Kency
You need to ensure that the target is not null. This is answered in [your previous question](http://stackoverflow.com/questions/3742523/propertynotfoundexception-target-unreachable-null-returned-null).
BalusC
Yes! it mean when i show property in form h:selectOnemenu value is a Integer type bean.user.getGroupID , then i change to bean.user.groups <== it not null but type are Groups , now i create method example public Integer getGroupdIDForBean(){this.groups.getGroupID} it return null, now i try solve it, thank you supported me !
Kency
Now i know my error but i can't solve it :( try again to solve this problem :D
Kency
What's the exact exception message now?
BalusC
i create 1 variable with Integer types , it insert ok but get error with transaction, and i know how it error, but i no have any idea for solved it, because Integer variable is not mapped to groups field in table user, should i change mapped type Groups to variable Integer type? it mean groupsid field in user table not reference to groups table. i need one suggest from you! Please help me BalusC
Kency
now i solved my problem by used Converter class :D , with override getAsObject method follow : public Object getAsObject(FacesContext context, UIComponent component, String value) { if(groups == null){ groups = new Groups(Integer.valueOf(value)); } return groups; }
Kency