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"/>

    </id>

    <natural-id>

        <property name="name"/>

        <property name="org"/>

    </natural-id>

    <property name="password"/>

</class>


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.


session.createCriteria(User.class)

    .add( Restrictions.naturalId()

        .set("name", "pawan")

        .set("org", "hb") 

    ).setCacheable(true)

    .uniqueResult();

Leave a Comment:
Search
Categories
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!