title: Hibernate second level cache example
body: <p>I am developing hibernate + ehcache program.</p>
  
  <pre><code>@Entity
  @Table(name = "pizza")
  public class Pizza implements Serializable{
      @Id
      @GeneratedValue
      private Integer id;
      private String name;
      private double price;
  
      public long getId() {
          return id;
      }
  
      public void setId(Integer id) {
          this.id = id;
      }
  
      public String getName() {
          return name;
      }
  
      public void setName(String name) {
          this.name = name;
      }
  
      public double getPrice() {
          return price;
      }
  
      public void setPrice(double price) {
          this.price = price;
      }
  
  }
  </code></pre>
  
  <p>ehcache.xml</p>
  
  <pre><code>  &lt;cache name="com.abp.osp.domain.Pizza"   
  maxElementsInMemory="100"   
  eternal="false"   
  timeToIdleSeconds="5"   
  timeToLiveSeconds="200" /&gt; 
  &lt;/ehcache&gt;
  </code></pre>
  
  <p>I have mentioned ehcache in bean.xml</p>
  
  <pre><code>   &lt;prop key="hibernate.cache.provider_configuration_file_resource_path"&gt;ehcache.xml&lt;/prop&gt;
          &lt;prop key="hibernate.cache.use_second_level_cache"&gt;true&lt;/prop&gt;
          &lt;prop key="hibernate.cache.use_query_cache"&gt;true&lt;/prop&gt;
          &lt;prop key="hibernate.cache.region.factory_class"&gt;net.sf.ehcache.hibernate.EhCacheRegionFactory&lt;/prop&gt;
           &lt;prop key="hibernate.cache.provider_class"&gt;net.sf.ehcache.hibernate.EhCacheProvider&lt;/prop&gt;
  </code></pre>
  
  <p>and my calling method within dao class is</p>
  
  <pre><code> Session session1=sessionFactory.openSession();  
  
            Pizza pizza2=(Pizza)session1.load(Pizza.class, 2);
            System.out.println("pizza2--"+pizza2.getName());  
            session1.close(); 
  
   Session session2=sessionFactory.openSession();  
  
            Pizza pizza4=(Pizza)session2.load(Pizza.class, 2);
            System.out.println("pizza4--"+pizza4.getName());  
            session2.close(); 
  </code></pre>
  
  <p>Output is:</p>
  
  <pre><code>Hibernate: select pizza0_.id as id0_0_, pizza0_.name as name0_0_, pizza0_.price as price0_0_ from pizza pizza0_ where pizza0_.id=?
  pizza2--Thin Crust
  Hibernate: select pizza0_.id as id0_0_, pizza0_.name as name0_0_, pizza0_.price as price0_0_ from pizza pizza0_ where pizza0_.id=?
  pizza4--Thin Crust
  </code></pre>
  
  <p>But it hit twice in database.I don't find anything wrong in my code.Please suggest me why it hit twice in database.</p>