Jeremy Stein
Jeremy Stein

Reputation: 19661

How to add a Hibernate property that's really a query

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?

Upvotes: 1

Views: 991

Answers (2)

RMorrisey
RMorrisey

Reputation: 7739

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.

Upvotes: 1

ChssPly76
ChssPly76

Reputation: 100831

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.

Upvotes: 1

Related Questions