views:

161

answers:

3

Well, I have implemented a distinct query in hibernate. It returns me result. But, while casting the fields are getting interchanged. So, it generates casting error. What should be the solution?

As an example, I do have database, "ProjectAssignment" that has three fields, aid, pid & userName. I want all distinct userName data from this table. I have applied query :

select distinct userName, aid, pid from ProjectAssignment

Whereas the ProjectAssignment.java file has the fields in sequence aid, pid & userName. Now, here the userName is first field in output. So, Casting is not getting possible.

Also, query :

select aid, pid, distinct userName from ProjectAssignment

is not working.

What is the proper query for the same ? Or what else the solution ?

The code is as below :

System Utilization Service Bean Method where I have to retrieve data :

public List<ProjectAssignment> getProjectAssignments() {
        projectAssignments = ProjectAssignmentHelper.getAllResources(); //Here comes the error
        return projectAssignments;
    }

ProjectAssignmentHelper from where I fetch Data :

package com.hibernate;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

public class ProjectAssignmentHelper {

    public static List<ProjectAssignment> getAllResources() {
        List<ProjectAssignment> projectMasters;

        Session session = HibernateUtil.getSessionFactory().openSession();
        Query query = session.createQuery("select distinct aid, pid, userName from ProjectAssignment");
        projectMasters = (List<ProjectAssignment>) query.list();
        session.close();

        return projectMasters;
    }
}

Hibernate Data Bean :

package com.hibernate;

public class ProjectAssignment  implements java.io.Serializable {

     private short aid;
     private String pid;
     private String userName;

    public ProjectAssignment() {
    }


    public ProjectAssignment(short aid) {
        this.aid = aid;
    }
    public ProjectAssignment(short aid, String pid, String userName) {
       this.aid = aid;
       this.pid = pid;
       this.userName = userName;
    }

    public short getAid() {
        return this.aid;
    }

    public void setAid(short aid) {
        this.aid = aid;
    }
    public String getPid() {
        return this.pid;
    }

    public void setPid(String pid) {
        this.pid = pid;
    }
    public String getUserName() {
        return this.userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}

Error :

For input string: "userName"

java.lang.NumberFormatException: For input string: "userName"
 at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
 at java.lang.Integer.parseInt(Integer.java:447)
 at java.lang.Integer.parseInt(Integer.java:497)
 at javax.el.ArrayELResolver.toInteger(ArrayELResolver.java:375)
 at javax.el.ArrayELResolver.getValue(ArrayELResolver.java:195)
 at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:175)
 at com.sun.faces.el.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:72)
 at com.sun.el.parser.AstValue.getValue(AstValue.java:116)
 at com.sun.el.parser.AstValue.getValue(AstValue.java:163)
 at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:219)
 at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:102)
 at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:190)
 at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:178)
 at javax.faces.component.UICommand.getValue(UICommand.java:218)
 at org.primefaces.component.commandlink.CommandLinkRenderer.encodeMarkup(CommandLinkRenderer.java:113)
 at org.primefaces.component.commandlink.CommandLinkRenderer.encodeEnd(CommandLinkRenderer.java:54)
 at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:878)
 at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:70)
 at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:54)
 at org.primefaces.component.datatable.DataTableRenderer.encodeTable(DataTableRenderer.java:525)
 at org.primefaces.component.datatable.DataTableRenderer.encodeMarkup(DataTableRenderer.java:407)
 at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:193)
 at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:878)
 at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:70)
 at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:54)
 at org.primefaces.component.tabview.TabViewRenderer.encodeContents(TabViewRenderer.java:198)
 at org.primefaces.component.tabview.TabViewRenderer.encodeMarkup(TabViewRenderer.java:130)
 at org.primefaces.component.tabview.TabViewRenderer.encodeEnd(TabViewRenderer.java:48)
 at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:878)
 at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1620)
 at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
 at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:848)
 at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1613)
 at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1616)
 at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1616)
 at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:380)
 at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:126)
 at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:127)
 at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
 at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
 at javax.faces.webapp.FacesServlet.service(FacesServlet.java:313)
 at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
 at org.apache.catalina.core.ApplicationDispatcher.doInvoke(ApplicationDispatcher.java:802)
 at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:664)
 at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:497)
 at org.apache.catalina.core.ApplicationDispatcher.doDispatch(ApplicationDispatcher.java:468)
 at org.apache.catalina.core.ApplicationDispatcher.dispatch(ApplicationDispatcher.java:364)
 at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:314)
 at org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:783)
 at org.apache.jsp.welcome_jsp._jspService(welcome_jsp.java from :59)
 at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:109)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
 at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:406)
 at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:483)
 at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:373)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
 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:332)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:233)
 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)
+1  A: 

Why do you want to use HQL?

The idea of Hibernate is to work with entities and not with tables. Ideally, you would load the entities and iterate through them getting the fields you want.

I would suggest you to use Hibernate Criteria and Criterion to that query.

Criteria crit = session.createCriteria(ProjectAssignment.class);
List projectAssignments = crit.list();

And then iterate through the list getting the fields you want.

pakore
In my experience the Criteria (and DetachedCriteria) don't yet have the full functionality you can get in writing your own HQL statements. Also, your criteria here doesn't address the distinct constraint. Finally, HQL still deals with the entities and not the tables since in HQL you query against the entities and their properties, not against tables and columns.
digitaljoel
Sarang
+1  A: 

First of all, if you use projections like in:

select distinct aid, pid, userName from ProjectAssignment

You will get an Object[] as result (or a List<Object[]>), not a List<ProjectAssignment>. If you want to get strong typed objects as result when using projections, you should use the select NEW expression (assuming you provide the proper constructor):

select new com.hibernate.ProjectAssignment(...) from ProjectAssignment.

Secondly, I don't get what you actually want. From the plain english description, the query would be:

select distinct userName from ProjectAssignment

But I'm not sure this is what you expect. Maybe if you clarify in plain english what the expected result is I could help further.

Thirdly, the current problem has NOTHING to do with Hibernate nor casting:

java.lang.NumberFormatException: For input string: "userName"

You are just trying to format a string that is not a number as a number.

Pascal Thivent
+1  A: 
Query query = session.createQuery("select distinct aid, pid, userName from ProjectAssignment");

Actually, query.list() will return an instance of ArrayList containing Array of Objects as each element. And each element on array contains value for each column.

e.g. query.list().get(0) will return an array of three objects

array[0] = value of aid
array[1] = value of pid
array[2] = value of userName

so, List<Object[]> can not be cast to List<ProjectAssignment>

One possible solution is implement ResultTransformer

something like this.........

First tell Hibernate what transformer to use

query.setResultTransformer(new ProjectAssignmentTransformer());

Now implementation

class ProjectAssignmentTransformer implements ResultTransformer {

@Override
public Object transformTuple(Object[] tuples, String[] aliases) {
            Object aid = tuples[0];
            Object pid = tuples[1];
            Object userName = tuples[2];
             /* construct ProjectAssignment instance using appropriate args*/
    return new ProjectAssignment (aid, pid, (String) userName);
}

@Override
public List transformList(List collection) {
    List<ProjectAssignment> assignments = new ArrayList<ProjectAssignment>();
    for(Object o : collection)
    {
        assignments.add((ProjectAssignment)o);  
    }
    return assignments;
}

}

After this you will be able to cast to List<ProjectAssignment>.

Hope this helps!

-SE

becomputer06
Thank you very much for this solution.
Sarang
I just want to solve the casting error that I got from it.
Sarang