The real difference between the get and load methods of session in Hibernate

Source: Internet
Author: User

Recently in the Learning Shh framework of Hibernate, the Get and load methods of the session, a little confused, do not know where the difference, or the difference between them is not deep. So Baidu a bit, the result of the problem came. The results of Baidu and the actual test results are very large. The main idea is that the Get method is inconsistent with the actual running results.

Let's start with the idea that:

    • Get does not support lazy,load support lazy;
    • When the data does not exist, get returns Null,load throws a Objectnotfoundexception exception.
    • The Load method can return an instance of a proxy class for an entity, and the Get method directly reads the database, so it returns the entity class directly (the claim for Get is wrong)
As for the first article, I believe that we do not have much doubt. Let me give you an example: lazy means to execute an SQL statement when it is used.
    1. User user = (user) session.load (user).      Class,"4028981b41174a690141174a6c6d0003");
This code does not execute the database query, but only when the user is used to execute the database query. Therefore, SQL statements are not generated immediately.
    1. User user = (user) session.get (user).       Class, "4028981b41174a690141174a6c6d0003");
The code above immediately executes the database query (if there are no instances in the cache).

And the next question, to be clear, is to first understand a problem--session the process of loading an entity object:

First, a level two cache is maintained in Hibernate. The first level of caching is maintained by the session instance, which is a transaction-scoped cache. It maintains data for all associated entities of the session, also known as internal caches. The second-level cache exists at the sessionfactory level, which is a process-wide or cluster-wide cache that is shared by all current session instances constructed by this sessionfactory.

For performance reasons, to avoid unnecessary database access, the session will be queried in the cache before invoking the database query function. First-level cache (internal cache), the entity type and ID to find, if the first-level cache lookup hit, and the data state is legitimate, it is returned directly. The session is then searched in the current "nonexists" record, and Null is returned if the same query condition exists in the "nonexists" record. "Nonexists" records the current session instance in all previous query operations, failed to query the valid data query criteria (equivalent to a query blacklist list). As a result, if an invalid query condition recurs in the session, you can quickly make a judgment to get the best performance.

For the Load method, the internal cache is looked up first, if the hit, the instance is returned, and if no valid data is found in the internal cache, the second-level cache is queried and returned if the second-level cache hits. If no valid data is still found in the level two cache, initiate a database query operation (Select SQL). Returns the entity class if the query is Proxy Object, if the query does not find the corresponding record, the information of this query is recorded in "Nonexists", and throws a Objectnotfoundexception exception. For the Get method, Many of the books, the Web blogs are wrong。 The Get method is also the first to find the internal cache, if hit, then return, or initiate a database query operation, if the query to, then return the entity class object, if the query did not find the corresponding record, the information of this query is recorded in "Nonexists", and returns NULL. So what the web says is "when someone modifies the data, the load may not read the latest data, and get will definitely read the latest modified data." not establishedOf       This means that the Get method is not necessarily the entity class object, nor does the Load method return the Entity proxy class object. The above view is I pass the test to arrive, has the code to have the picture to have the truth:
  1. Package com.bjpowernode.hibernate;
  2. Import Java.util.Date;
  3. Import Junit.framework.TestCase;
  4. Import org.hibernate.ObjectNotFoundException;
  5. Import org.hibernate.Session;
  6. Import org.hibernate.Transaction;
  7. /**
  8. * Session Test Class
  9. *
  10. * @author Longxuan
  11. *
  12. */
  13. Public class Sessiontest extends TestCase {
  14. public void Testequals () {
  15. Session session = null;
  16. try {
  17. //Get session
  18. Session = Hibernateutils.getsession ();
  19. //Open transaction
  20. Session.begintransaction ();
  21. System.out.println ("\n\n\n\n");
  22. try {
  23. //Verify that the Get returns Null,load throw Objectnotfoundexception exception when data is not found
  24. System.out.println (Session.get (User.   class, "123"));
  25. System.out.println (Session.load (User.   class, "123"));
  26. } catch (Objectnotfoundexception e) {
  27. System.out.println ("Load method throws Objectnotfoundexception exception");
  28. }
  29. System.out.println ("\ n");
  30. //Verify that Load returns an entity class object, not a proxy object
  31. {
  32. User User1 = (user) session.get (user).   Class,"4028981b41174a690141174a6c6d0003");
  33. User User2 = (user) session.load (user).   Class,"4028981b41174a690141174a6c6d0003");
  34. System.out.println ("user1:" + user1.getclass (). Getsimplename ());
  35. System.out.println ("user2:" + user2.getclass (). Getsimplename ());
  36. System.out.println ("User1 and User2 are the same object:" + user1.equals (user2));
  37. }
  38. System.out.println ("\ n");
  39. Session.clear (); //Clear Session
  40. //Verify get can also return a proxy class object without necessarily returning an entity class object
  41. ///Verify that the Get method finds the cache first (if there is no output SQL statement, the get finds the cache)
  42. {
  43. User User3 = (user) session.load (user).   Class,"4028981b41174a690141174a6c6d0003");
  44. User User4 = (user) session.get (user).   Class,"4028981b41174a690141174a6c6d0003");
  45. System.out.println ("User3:" + user3.getclass (). Getsimplename ());
  46. System.out.println ("user4:" + user4.getclass (). Getsimplename ());
  47. System.out.println ("User3 and User4 are the same object:" + user3.equals (user4));
  48. }
  49. Session.gettransaction (). commit ();
  50. } catch (Exception e) {
  51. E.printstacktrace ();
  52. Session.gettransaction (). rollback ();
  53. } finally {
  54. Hibernateutils.closesession (session);
  55. }
  56. }
  57. }

Run the result diagram:
There is also an interesting phenomenon:
    1. User User5 = (user) session.load (user).        class, "123");
    2. System.out.println (User5.getid ());
Running results direct output 123 from the results, it can be seen that the first 2 lines of code do not perform database operations. Since load will store a map object in the Hibernate cache, the map key is the value of the ID, but when you GetID (), it will go to the first-level cache to take the map key value, just found, so no more to execute the database query. and will not report any mistakes. The results are as above.

The real difference between the get and load methods of session in Hibernate

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.