Deep understanding of MyBatis-level cache _java

Source: Internet
Author: User

The client sends the same SQL query to the database server, and if it accesses the database every time, it can cause performance degradation.

So how to improve it?

MyBatis provides us with a first-level caching strategy

In a sqlsession between open and close, the Sqlsession object (in fact, executor) will maintain a cached object, when querying the data, first look for the existence of the data from the cache, there is directly out, does not exist, to the database to send SQL query, The data after the query is then cached and returned to the program.

There is a problem:

If a program changes the data of the database to be queried during the first and second queries, it will cause the read data to be wrong.

Dirty reads, in fact, mybatis the cache after sqlsession executes the commit () method. The second time you go to the query, you will still be querying from the database.

You can also manually call the Sqlsession ClearCache () method to clear the cache

Small example:

@Test public
  void TestCacheLever1 () throws exception{
    sqlsession session = Factory.opensession ();
    Usermapper mapper = Session.getmapper (usermapper.class);
    First request, the user with Query id 1
    = Mapper.finduserbyid (1);
    SYSTEM.OUT.PRINTLN (user);
    Changing the data will empty the cache
    user.setusername ("yyyy");
    Mapper.updateuser (user);
    Session.commit ();
    The second query will look for
    User user2 = Mapper.finduserbyid (1) from the cache;
    System.out.println (user2);
    Session.close ();
  }

Problem:

If the sqlsession is closed, the cache is emptied. How does this use caching to improve efficiency?

OK, the next article will introduce you to MyBatis level two cache.

The above is a small series to introduce the MyBatis cache, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.