|
Good Question. Hibernate can make certain optimizations all the time:
- Caching objects. The session is a
transaction-level cache of persistent objects. You may also enable a
JVM-level/cluster cache to memory and/or local disk.
- Executing SQL statements later, when needed.
The session never issues an INSERT or UPDATE until it is actually
needed. So if an exception occurs and you need to abort the
transaction, some statements will never actually be issued.
Furthermore, this keeps lock times in the database as short as possible
(from the late UPDATE to the transaction end).
- Never updating unmodified objects. It is very
common in hand-coded JDBC to see the persistent state of an object
updated, just in case it changed.....for example, the user pressed the
save button but may not have edited any fields. Hibernate always knows
if an object's state actually changed, as long as you are inside the same (possibly very long) unit of work.
- Efficient Collection Handling. Likewise, Hibernate only ever inserts/updates/deletes collection rows that actually changed.
- Rolling two updates into one. As a corollary to (1) and (3), Hibernate can roll two seemingly unrelated updates of the same object into one UPDATE statement.
- Updating only the modified columns. Hibernate knows exactly which columns need updating and, if you choose, will update only those columns.
- Outer join fetching. Hibernate implements a very efficient outer-join fetching algorithm! In addition, you can use subselect and batch pre-fetch optimizations.
- Lazy collection initialization.
- Lazy object initialization. Hibernate can use runtime-generated proxies (CGLIB) or interception injected through bytecode instrumentation at build-time.
A few more (optional) features of Hibernate that your handcoded JDBC may or may not currently benefit from
- second-level caching of arbitrary query results, from HQL, Criteria, and even native SQL queries
- efficient PreparedStatement caching (Hibernate always uses PreparedStatement for calls to the database)
- JDBC 2 style batch updates
- Pluggable connection pooling
Hopefully
you will agree that Hibernate approaches the parsimony of the best
hand-coded JDBC object persistence. As a subscript I would add that I
have rarely seen JDBC code that approaches the efficiency of the "best
possible" code. By contrast it is very easy to write efficient
data-access code using Hibernate.
|