Restrict by class in query

#1

I have the following bit of code:

public List<Folder> findFolderByName(String folderName) {
  TypedQuery<Folder> byNameQuery = this.entityManager.createQuery("SELECT f FROM Entry f WHERE f.name=:name", Folder.class);
  return byNameQuery.setParameter("name", folderName).getResultList();
}

I would have assumed that the class parameter would cause results to be restricted to only objects of type Folder (I have a class hierarchy in which both Link and Folder are subclasses of a common root Entry which is where the name parameter occurs). 

When I put both a folder and a link with the same name into the database, and execute the above query, I get a List<Folder> with two entries in it according to .size(). If I iterate using a foreach loop, I only get the folder. I can, however do a .get(1) call to fetch the result. Am I doing something wrong to make sure that I only get folders in my result set?

#2

It is unclear what you want to retrieve (Folder, Link, both?) and what you get in the result list (Folder, Link, both?).

ObjectDB Support
ObjectDB - Fast Object Database for Java (JPA/JDO)
#3

I want only Folder, I get both Folder and Link in the result list.

#4

Does Link extend Folder?

ObjectDB Support
ObjectDB - Fast Object Database for Java (JPA/JDO)
#5

As indicated in the original post, both Link and Folder are subclasses of Entry. Neither extends the other

-dh

#6

This is an unexpected behavior.

Could you please provide a sample test case that demonstrates it?

ObjectDB Support
ObjectDB - Fast Object Database for Java (JPA/JDO)
#7

I've attached a demonstration set of classes that show the issue.

#8

Your query is invalid. Instead of:

    em.createQuery("SELECT f FROM Entry f WHERE f.name=:name", Folder.class);

You should use:

    em.createQuery("SELECT f FROM Folder f WHERE f.name=:name", Folder.class);

and then you should get only Folder instances as expected.

The result type argument has no effect on the query. Actually, according to the JPA JavaDoccreateQuery(qlString, resultClass)EntityManager's methodCreate an instance of TypedQuery for executing a Java Persistence query language statement.See JavaDoc Reference Page... an IllegalArgumentException has to be thrown if the specified result type doesn't match the query string, but currently ObjectDB silently ignores such a mismatch.

ObjectDB Support
ObjectDB - Fast Object Database for Java (JPA/JDO)

Post Reply

To post a reply and/or subscribe to update notifications - please login