Queries by natural identifier by R4R Team

In the most queries, including criteria queries, query cache is not efficient because query cache invalidation occurs too frequently. There is a special kind of query where you can optimize the cache invalidation algorithm: lookups by a constant natural key. In some applications, this kind of query occurs frequently. The criteria API provides special provision for this use case.

In the First, map the natural key of your entity using <natural-id> and enable use of the second-level cache.

<class name="User">

    <cache usage="read-write"/>

    <id name="id">

        <generator class="increment"/>



        <property name="name"/>

        <property name="org"/>


    <property name="password"/>


This functionality is not intended for use with entities with mutable natural keys. Once we enabled the Hibernate query cache, the Restrictions.naturalId() it means we  allows you to make use of the more efficient cache algorithm.


    .add( Restrictions.naturalId()

        .set("name", "pawan")

        .set("org", "hb") 



Leave a Comment:
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!