tags:

views:

133

answers:

2

We're using Hibernate to load objects that meet certain criteria. If the user decides to view the details on one of the objects, I want to pull up some additional information about the object. One of the "attributes" I'd like to show will require a fairly complex SQL query, but evaluates to a simple boolean.

What's the right way to do this with Hibernate? Is there a way to indicate a property whose value is the result of a SQL query? If so, is there a way to prevent the query from being invoked until it's needed?

Or am I approaching this incorrectly?

+1  A: 

Depending on how complex that query is and what it returns, you can either use a formula or map your "attribute" as a separate entity (many-to-one) that will be lazy-loaded.

ChssPly76
do you have an example of the second option?
zvolkov
I edited my question to note that the query evaluates to a simple boolean. So, the formula sounds appropriate, but would it be executed for each object that was loaded, even if I never use that field?
Jeremy Stein
OK, Google answered my question. Lazy formula is not supported until Hibernate 3.
Jeremy Stein
Hibernate 3.3.2 is the current version. And lazy formula evaluation is very much supported; however it would require bytecode instrumentation (like any other non-association property in order to be lazy loaded)
ChssPly76
+1  A: 

How about defining a named query? In hibernate annotations, you can have an annotation on an entity class which looks like:

@NamedNativeQuery(name = "user.someUsers", query = "select u.* from users u where someparam = :someValue...", resultClass = User.class)

I'm sure you can do it in hibernate's XML config also but I don't know the syntax offhand. This would not be a mapped property on the object itself, but you could use this query whenever you want to get back that specific piece of information.

RMorrisey