Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

java - Iterate List<Object> from Join query using JPA / PLay

This is my query using entity manager. Trying to join 2 table with play framework and jpa.

 List<Object> joinQryResult = JPA.em().createNativeQuery(
         "select e.elementname as elementname, " +
         "c.comparetype as comparetype, " + 
         "jd.matchvalue as matchvalue " +
         "from details jd " +
         "join elements e on jd.elementnamerid = e.rid " +
         "join comparers c on jd.comparetyperid = c.rid " +
         "where jd.rid = " + temp.rid).getResultList();

 Not sure how to iterate and get the values from List<Object>

I tried this

List<MyClass> myClass = (List<MyClass>)(Object)joinQryResult;


for(MyClass myC:jd)
{
 System.out.println(myC.ElementName); //intellisense shows the property here
}

MyClass definition: ttrying to convert List to this type

public class MyClass {

    public String ElementName;

    public String CompareType;

    public String MatchValue;

    public JobDetails(String ElementName, String CompareType, String MatchValue)
    {
        this.ElementName = ElementName;

        this.CompareType = CompareType;

        this.MatchValue = MatchValue;
    }
}

Get this error

ClassCastException occured : [Ljava.lang.Object; cannot be cast to models.MyClass
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The result of the query will be a List with the elements of the objects being the corresponding object type.

You could do as follow to map to your object

    List<Object[]> results = query.getResultList();
    JobDetails jobDetail = null;
    for (Object[] objects : results) {
        jobDetail = new JobDetail((String) objects[0],(String) objects[1],(String) objects[2])
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...