Search code examples
ormopenjpa

Native Query Mapping on the fly openJPA


I am wondering if it is possible to map a named native query on the fly instead of getting back a list of Object[] and then looping through and setting up the object that way. I have a call which I know ill return a massive data set and I want to be able to map it right to my entity. Can I do that or will I have to continue looping through the result set.

Here is what I am doing now...

List<Provider> ObjList = (List<Provider>) emf.createNativeQuery(assembleQuery(organizationIDs, 5)).getResultList();

That is my entity, the List (my entity is the provider). Normally I would just return a List<Object[]> and then I would loop through that to get back all the objects and set them up as new providers and add them to a list....

//List<Provider> provList = new ArrayList<Provider>(); 
/*for(Object[] obj: ObjList)
{
    provList.add(this.GetProviderFromObj(obj));
}*/

As you can see I commented that section of the code out to try this out. I know you can map named native queries if you put your native query in the entity itself and then call it via createNamedQuery. I would do it that way, but I need to use the IN oracle keyword because I have a list of ID's that I want to check against. It is not just one that is needed. And as we all know, native queruies don't handle the in keyword to well. Any advice?

Sigh, If only the IN keyword was supported well for NamedNativeQueries.


Solution

  • Assuming that Provider is configured as a JPA entity, you should be able to specify the class as the second parameter to your createNativeQuery call. For example:

    List<Provider> ObjList = (List<Provider>) emf.createNativeQuery(assembleQuery(organizationIDs, 5), Provider.class).getResultList();
    

    According to the documentation, "At a minimum, your SQL must select the class' primary key columns, discriminator column (if mapped), and version column (also if mapped)."

    See the OpenJPA documentation for more details.