-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: Persistence Context For Queries
PostPosted: Sat Aug 14, 2010 2:56 am 
Beginner
Beginner

Joined: Wed Aug 22, 2007 5:53 am
Posts: 38
In Java Persistence With Hibernate book (2007 edition), on page 390, its mentioned that "The same is true if a query is executed through one of the Hibernate interfaces. Hibernate reads the result set of the query and marshals entity objects that are then returned to the application. During this process, Hibernate interacts with the current persistence context."

However the above statement looks incorrect to me as :
Code:
Session session = sessionFactory.openSession();
   Transaction tx = session.beginTransaction();
    Query query = session.createQuery("from Item i where i.itemId=1");
    Iterator it = query.list().iterator();
    while (it.hasNext ()){
      Item i = (Item) it.next();
      System.out.println(i.getItemDesc());
    }
   
    query = session.createQuery("from Item i where i.itemId=1");
    it = query.list().iterator();
    while (it.hasNext ()){
      Item i = (Item) it.next();
      System.out.println(i.getItemDesc());
    }
   
   tx.commit();
   session.close();


In this example: SQL is executed 2 times...


Top
 Profile  
 
 Post subject: Re: Persistence Context For Queries
PostPosted: Sat Aug 14, 2010 5:39 am 
Expert
Expert

Joined: Wed Mar 03, 2004 6:35 am
Posts: 1240
Location: Lund, Sweden
Quote:
In this example: SQL is executed 2 times...


You'll have to configure Hibernate to use a second-level cache and also set a flag on the query that the result should be cached: query.setCacheable(true).

No matter if the query is cached or not you will also see that the Item i variable in the two while loops is actually the same instance.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.