Having read theory of Hibernate, I've encountered the idea several times that in an ideal world, you should not mix Hibernate with raw SQL queries, for several reasons such as Hibernate being unable to recognise changes that have been performed in this manner which can have an impact when it comes to flushing properly.
I have been given the task of attempting to optimise and improve several classes which communicate with the database but do so without going through Hibernate. They directly use the JdbcTemplate to run the query, and I've noticed that this has been more commonly done for update statements.
Is this deliberate and good design, for some reason such as only a select number of fields are being updated and the object in the database is quite large, or should I aim to refactor these classes so that they utilise DAO layer classes to perform these update queries?
Personally, after some years with hibernate (which I tent to love a lot more than hate), I see two main reason for when you want to make hibernate only queries. Potentially moving to a different database, caching of the queries would be another. And both, to me, are very valid reasons, if this matters for you. You will probably get more answers here why this is a good thing, so I'm not going to tell you more about this. Instead, I might tell you why this is not always possible with cases that I actually faced.
Spatial queries - geometry and geography data types; there are lots of databases that support this and sometimes it is a very handy feature - I really like MSSQL in this regard, their indexing strategy, how this is handled, etc. There is no way to make these queries in hibernate, that has very limited facilities for this.
Hibernate sometimes hides a lot more that it should (it's not it's fault); if you don't understand what queries will hibernate generate, you might be often very surprised. I suggest you check the actual queries all the time. Another example is when you work with pessimistic/optimistic locks - always look at the queries, it's not always the case where hibernate might generate what you would expect... (AzureSQL does not have select for update
- it uses hints
, like with row lock
, etc - giving you zero assurance that a row will be locked, without a proper index and few resources an entire table or page could be locked)
That being said, I always try to favor Hibernate in this regard, if something does not work as I expect - I use native queries and such IMHO this perfectly shaped world simply does not exist.
There are many benefits in using hibernate with HQL
(Hibernate Query Language) instead of Native Queries (or Hibernate instead of JDBC), I am stating 3 of them:
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With