Using views in Hibernate

We have been thinking recently about using some SQL views in our Hibernate application backed by postgresql. It looks feasible and even it enables great possibilities. Below quick snapshot from my testing app showing how it works.

Entities

We start from the simple model with mapped superclass which is the base for our all entities:

View

I wanted to get with HQL all transactions with seller field set to some id from this view.

This example might look senseless, but here is the motivation: we assume that this view shows only some companies, where some condition is very complex and very hard to achieve in plain HQL. And we finally want to see all transaction of these some companies.

I extracted the following class as the mapped superclass for view object (it doesn’t need classname because it won’t have subclasses):

@Immutable excludes this entity from session flushes, even if it will be accidentially changed by the developer.

@Subselect excludes this entity from auto schema update (if you use it - I do).

Queries

Having CompanyView defined as the standard Hibernate entity, we may now query it as the other table:

from CompanyView

Moreover, to achieve our target we can use implicit join. To use explicit join we’d need to have a relation to CompanyView declared on Transaction. I haven’t experimented with this, but the implicit join works well:

from Transaction at, CompanyView cv where at.seller.id=cv.id

As promised, it will be quick, and it ends here. Have a nice try with views and Hibernate.