I've been using the HQL dynamic instantiation in my listing methods.
For example:
session.createQuery("select new Summary(d.id, d.name, d.shortDesc) from ...");
Summary is a shortened version of the full class, used to get just the fields required to build a listing display and provide the key to the full objects. It is just a listing class and not intended to be a persistent entity.
Some of the listing queries I'm making have become more complex and dynamic so I've started using Criteria instead of Query. As far as I can tell, Criteria doesn't support the dynamic instantiation like HQL does (if I'm wrong about that please tell me). So instead I've used projection to get the subset of fields I'm interested in.
For example:
// Project just the properties required for summaries.
Projection properties =
Projections.projectionList()
.add(Projections.id())
.add(Property.forName("name"))
.add(Property.forName("shortDesc"));
// Create the selection criteria for the listing.
Criteria selectCriteria =
session.createCriteria(entityName)
.add(criterion)
.setProjection(properties);
Which generates a listing of Object arrays. So, I iterate over the results list and turn it into the Summary objects by doing:
List<Object[]> rawResults = selectCriteria.list();
List<Summary> results = new ArrayList<Summary>();
for (Object[] row : rawResults)
{
results.add(new Summary((Long)row[0], (String)row[1], (String)row[2]));
}
I've been wondering if there's a neater OO way of doing this than working with the array of objects. I'd be interested to hear any suggestions.
Do you think it would be possible/beneficial to have some kind of ObjectProjection class in Hibernate? This might work something like this:
// Project the summary class.
Projection summaryProjection =
Projections.objectProjection("new Summary(id, name, shortDesc)");
Hibernate would use this to extract the named fields and build the summary listing objects for me.
Rupert Smith
|