overviewRetrieving object from database is one of the most interesting andcomplex parts of working with hibernate. Hibernate provides thefollowing ways for getting objects out of the database: Retrieving by identifier. Using Hibernate Query Language (HQL) which is a fully Object oriented query language. Using Hibernate Criteria API – Provides a Type safe and OO way to perform queries without String manipulation Using Native SQL query Hibernate takes care of mapping the resultsets.
Retrieving Object by IdentifierRetrieving by identifier:User user = (User) session.get(User.class, userID)It uses cache when it is already loaded Get() method returns nullWhen it cannot find the object in cache or Database.User user = (User) session.load(User.class, userID)If Load() can’t find the Object then it throws an Exception. Retrieving object by identifier isn’t a flexible way as using arbitrary queries
Hibernate Query Language HQL is an Object Oriented dialect of the familiar relational query language SQL. It’s similar to OQL and EJB-QL. It’s not a DML like SQL. It’s used only for object retrieval Query q = session.CreateQuery (“from User u where u.firstName = :fname”); q.getString(“fname”,”Ram”); List result = q.list();
Using Criteria Object• Once the desired criteria tree is built it’s executed against the DB.• Query syntax is parsed and validated at compile time• Good aspect about Hibernate Criteria API is the Criterion framework which can be extended by the user.Criteria criteria = session.createCriteria(User.class);Criteria.add( Expression.like(“firstname”. “Ram”));List result = criteria.list();Criteria tree of criterion instancesExpression static factory methods that return Criterion instances
QBE – Query by ExampleApplication supplies instance of the queried class with Criterionproperty value set, the Query then returns all persistent instanceswith matching property values.User exampleUser = new User();exampleUser.setName(“SAM”);Criteria criteria = session.createCriteria(User.class);Criteria.add( Example.create(exampleUser));List result = criteria.list();Typical use is a search screen that allows user to specify a range ofproperty values to be matched by the returned resultsets.
Fetching Strategies Eager fetching or Join fetching – fetches data in a single SELECT, using an OUTER JOIN . Immediate fetching – The associated object is fetched immediately, using a sequential database read. Lazy or Select fetching –second SELECT is used to fetch the data. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association. Batch fetching - an optimization strategy for select fetching, fetching a batch of objects or collections.
Fetching CollectionsFor fetching collection lazy fetching is the best. <set name=”bids” lazy=”true” batch-size = “9”> <key column=”ITEM_ID”/> <one-to-many class= “BID”/></set> Outer-Join – true eager fetching Lazy=”true” lazily fetches the collection. Neither attribute specified fetched from 2nd level cache or immediate extra SQL query
Setting the fetch depthWe can set the maximum fetch depth globally. This settingcontrols the number of outer-joined tables that hibernate willuse in a single query.For this we have to configure in hibernate.cfg.xml globallyEg:hibernate.max_fetch_depth=2Based on the fetch depth declared it will generate thequery with joins.
The Query CacheQuery result sets may also be cached. This is only useful forqueries that are run frequently with the same parameters.To use the query cache you must first enable it: hibernate.cache.use_query_cache=trueIt creates Two new cache regions org.hibernate.cache.StandardQueryCache holding cached query result sets UpdateTimestampsCache holding timestamps of the most recent updates to queryable tables
Tuning Object retrieval Enable the HQL log. Set hibernate,show_sql=true Step through your application use case by use case and note how many and what SQL statements Hibernate executes If join operation are too complex and slow set outer join to false for <many-to-one> If too many SQL statements are executed use Lazy=”false” for all collection mapping.