It's a frequent requirement to select (id, name) tuples into a list in order to, for example, construct a list of URLs, where the name will be the link string and the id will be a query string parameter. This is easy enough to do in HQL. I went one step further and created an object with an id and a name property which I can select into:
select new NamedId(obj.id, obj.name) from my.domain.Object obj;
However, as a convenience, mostly for debugging but occasionally for production functionality, it would often be nice to know the concrete class that the id and name represents. This is particularly true when executing a polymorphic query via a query on a superclass.
I've got a constructor for NamedId that accepts as Class as a 3rd parameter, but I cannot figure out any syntax that will populate it correctly. If the object being queried is mapped with a discriminator, then I can do the following if the 3rd parameter in the NamedId constructor is a String
select new NamedId(obj.id, obj.name, obj.class) from my.domain.Object obj;
That places the discriminator string into the 3rd parameter. Arguably, that is sufficient to satisfy the vast majority of my debugging needs, since I usually know which basic class hierarchy my objects are queried out of. However, most of my domain objects do implement a Named interface which provides a name property, so what I'd really like is a polymorphic query that would return info about every Named object in the database, and I'd need to know the concrete class name for that to be useful, since I'd have duplicate ids from many tables.
select new NamedId(obj.id, obj.name, obj.class) from Named obj;
This would be useful because I could actually hydrate entities out of the database without knowing any more information than what is returned in that query by simply doing this: "from " + namedId.getClazz().getName() + " obj where obj.id = :objId"
Is there some undocumented HQL feature which would put the the most concrete class for any entity into the query results? It is definitely not in the core hibernate documentation or the Java Persistence with Hibernate book, so far as I can find.
|