Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Convert JPA Query getResultList to Array

843833Oct 13 2009 — edited Oct 14 2009
I have been struggling with this problem for several hours now. All I have succeeded in doing is attempt every possible way to convert a List into an array and I just get errors.
	// create native SQL query
	Query q = em.createNativeQuery("SELECT * FROM Project p");

	// get and process the results
	List<Project> list = q.getResultList();
        Project[] retVal = new Project[list.size()];
	for (int i = 0; i < list.size(); i++)
	{
	    retVal[i] = list.get(i);
	}
One would assume this to work, however this generates a ClassCastException, cannot convert Object to Project, oddly because as far as I can see everything in the code is strongly typed. I think Persistence fills the typed List with Object and not Project??

So I tried:
Project[] retVal = list.toArray(new Project[0]);
This generates an ArrayStoreException.

Finally I tried the basic, should generate x-lint warning:
Project[] retVal = (Project[])(list.toArray());
This also return ClassCastException, same reason as the first attempt.

I want my WebService function to return a standard Project[] not the java.lang.List class. But it seems JPA queries only support getting a List. I have googled to no end for a solution. Help appreciated!

Thanks.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 11 2009
Added on Oct 13 2009
2 comments
5,880 views