I like using Hibernate
for regular simple CRUD
operations.
However, I am trying to understand why anyone would resort to its Criteria
framework to assemble complex recordset criteria as opposed to simply creating a view at the database level.
E.g. here is a paraphrased snippet I am working with:
Criteria tableCriteria = session
.createCriteria(SomeEntity.class)
.add(Restrictions.eq("someID", someID))
.add(Restrictions.gtProperty("scoreOne", "scoreTwo"))
.add(Restrictions.gt("scoreThree", scoreThreeMin))
.add(Restrictions.or(Restrictions.eq("inactive", Boolean.FALSE), Restrictions.isNull("inactive"))).addOrder(Order.asc("ordCol"))
From the naked eye perspective, it is possible but let legible to discern what this filter definition is stipulating than to simply make a DB view where these restrictions could be expressed in the form of simpler WHERE
clauses.
Am I missing something? Is there an advantage to using Criteria vs. DB views that I am not aware of? Using views seems much cleaner. Is there a performance upside to Criteria?
3
The main benefit of using the Criteria
framework is programmatic query creation, and as Aaronaught implies, it’s much easier with Criteria
to run an arbitrarily complex query on many different RDBMSs than it is with a named view that would need to be created and maintained separately.
Depending on your situation (and for your example), a view may be more maintainable and easily optimized. HQL would certainly be easier to read.
0
From the database perspective, you are more likely to be able to write a better performing view. You may be able to layer views together, where some of the views contain distinct, reusable chunks of business logic. When approached this modular way you greatly reduce the probability of having outrageous numbers of views. And this should simplify things in the “thousands” of Java applications using them, reducing development, maintenance, and performance costs on the Java side.
This may work well in some environments where you are dealing with a single DBMS. This also lays the groundwork for use outside you java development group. There might be applications wanting to use other access methods, now or in the future.
Of course some DBMS’s may not optimize the layered views approach as well as mine. YMMV.