MyBatis Study Notes (ii) MyBatis caching mechanism

Source: Internet
Author: User

MyBatis Study notes Two

Before: MyBatis official Learning (Chinese) document Http://mybatis.github.io/mybatis-3/zh/index.html

First, to use MyBatis must use the officially supplied MyBatis jar package

Links: https://github.com/mybatis/mybatis-3/releases

The database used here is MySQL, so we also need the MySQL driver package,

Two, see MyBatis official introduction, said MyBatis support cache, level two cache. Here is the reason why I really want to learn mybatis.

You know, if you use the caching mechanism in the DAO layer in your project, your database pressure will be greatly optimized. The responsiveness of your program will also be greatly improved.

In MyBatis, the first-level cache has been turned on by default,

public static void Main (string[] args) throws exception{sqlsession session = Sqlsessionfactory.opensession ();    Usermapper usermapper = Session.getmapper (Usermapper.class);    User user = Usermapper.selectuserbyid (1);        User user2 = Usermapper.selectuserbyid (1);    System.out.println (User.getname ());        System.out.println (User2.getname ()); Session.close ();}

Here, we only create a new sqlsession, and then instantiate a usermapper query two times.

Then we can take a look at the console print bug

debug [main] - logging initialized using  ' Org.apache.ibatis.logging.log4j.Log4jImpl '  adapter. Debug [main] - pooleddatasource forcefully closed/removed all connections. Debug [main] - pooleddatasource forcefully closed/removed all connections. Debug [main] - pooleddatasource forcefully closed/removed all connections. Debug [main] - pooleddatasource forcefully closed/removed all connections. debug [main] - openning jdbc connectiondebug [main] - created  connection 27187756.debug [main] - ooo using connection [[email  Protected]]debug [main] - ==>  preparing: select * from user  where id = ? debug [main] - ==> parameters: 1 (Integer) Xiaoleixiaoleidebug [main] - resetting autocommit to true on jdbc  connection [[email protected]]debug [main] - closing jdbc connection [ [Email protected]] Debug [main] - returned connection 27187756 to pool.

From here I can see that although we have executed two queries in the code, the actual operation to get the data from the database is only one time.

Preparing:select * FROM user where id =?

Third, that is, there is a first-level cache, we can not consider. Then we'll focus on the level two cache.

By querying the data, I found that the level two cache is not so complex, just need to configure in the configuration file, OK,

Mybatis-config.xml

<?xml version= "1.0"  encoding= "UTF-8"  ?><! doctype configuration public  "-//mybatis.org//dtd config 3.0//en" "http://mybatis.org/ Dtd/mybatis-3-config.dtd "><configuration>        <settings ><setting name= "cacheenabled"  value= "true"/>    </settings>         <environments default= "Development" >         <environment id= "Development" >         <transactionmanager type= "JDBC"/>             <datasource type= "Pooled" >             <property name= "Driver"  value= "Com.mysql.jdbc.Driver"/>             <propertY name= "url"  value= "Jdbc:mysql://127.0.0.1:3306/mybatis"  />             <property name= "username"  value= "root"/>             <property name= "Password"  value= " Password "/>            </datasource>         </environment>    </environments >    <mappers>        <mapper  class= "Com.xcode.beens.mapperInterfaces.UserMapper"/>    </mappers></ Configuration>

We found. This configuration file with the previous configuration file, a lot of this stuff

<settings> <setting name= "cacheenabled" value= "true"/></settings>

Well, when I found out that as long as I was configuring such a sentence, the Labor Department really wanted to say: ' Scared the baby. '

Then I went back to the test and found it was no different. And then some operations will be error-

Org.apache.ibatis.cache.CacheException:Error serializing object. Cause:java.io.NotSerializableException:

When this anomaly happens, I know it's not that simple.

Then I looked up the information, found that the original is my been have a problem, the original to achieve level two cache, you must implement a serializable interface : Java.io.Serializable

To implement this interface for User.java :

Package Com.xcode.beens;import Java.io.serializable;public class User implements serializable{private static final long Serialversionuid = 8942594370466951584l;private int id;private string Name;private string sex;private string address; public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String Getsex () {return sex;} public void Setsex (String sex) {this.sex = sex;} Public String getaddress () {return address;} public void setaddress (String address) {this.address = address;}}

When everything is done, test again:

public static void Main (string[] args) throws exception{sqlsession session = Sqlsessionfactory.opensession (); Sqlsession Session2 = Sqlsessionfactory.opensession (); Usermapper usermapper = Session.getmapper (Usermapper.class); Usermapper userMapper2 = Session2.getmapper (Usermapper.class); User user = Usermapper.selectuserbyid (1); Session.commit ();//must be submitted here, otherwise it will be queried two times user User2 = Usermapper2.selectuserbyid (1); System.out.println (User.getname ()); System.out.println (User2.getname ()); Session.close (); Session2.close ();}

As we can see in this code, I instantiate two sqlsession here, and then different sqlsession instantiate different usermapper,

Two usermapper perform the same operation, all querying the database. , let's take a look at the console log:

debug [main] - logging initialized using  ' Org.apache.ibatis.logging.log4j.Log4jImpl '  adapter. Debug [main] - pooleddatasource forcefully closed/removed all connections. Debug [main] - pooleddatasource forcefully closed/removed all connections. Debug [main] - pooleddatasource forcefully closed/removed all connections. Debug [main] - pooleddatasource forcefully closed/removed all connections. Debug [main] - cache hit ratio [com.xcode.beens.mapperinterfaces.usermapper]:  0.0debug [main] - openning jdbc connectiondebug [main] - created  connection 12644844.DEBUG [main] - ooo Using Connection [[email  protected]]debug [main] - ==>  preparing: select * from user&Nbsp;where id = ? debug [main] - ==> parameters: 1 (Integer) Debug [main] - cache hit ratio [com.xcode.beens.mapperinterfaces.usermapper]:  0.5xiaoleixiaoleiDEBUG [main] - Resetting autocommit to true on  jdbc connection [[email protected]]debug [main] - closing jdbc  connection [[email protected]]debug [main] - returned connection 12644844  to pool.

We see this time, although we query the code two times, but really go to the database query, we have only queried once, that is, we are the second time to read the cache.

Note: Before I used annotations, I found that the cache didn't work at all, and then I checked and didn't find a way to use the two level cache using annotations

In other words, you must use the Usermapper.xml configuration file configuration to use level two caching.

Mybatis-config.xml needs to be modified to:

<?xml version= "1.0"  encoding= "UTF-8"  ?><! doctype configuration public  "-//mybatis.org//dtd config 3.0//en" "http://mybatis.org/ Dtd/mybatis-3-config.dtd "><configuration>        <settings ><setting name= "cacheenabled"  value= "true"/>    </settings><!- -  here to note that this typealiases can not be placed under the  environments  node, or will error  -->    < typealiases>         <typealias alias= "User"  type = "Com.xcode.beens.User"/>     </typealiases>          <environments default= "Development" >         <environment id= "Development" >        < Transactionmanager type= "JDBC"/>    &nbSp;       <datasource type= "Pooled" >             <property name= "Driver"  value= " Com.mysql.jdbc.Driver "/>            < Property name= "url"  value= "Jdbc:mysql://127.0.0.1:3306/mybatis"  />             <property name= "username"  value= "root"/>             <property name= "Password"  value = "Password"/>            </datasource>         </environment>    </environments >    <mappers>        <mapper  Resource= "Com/xcode/beens/mapperinterfaces/usermApper.xml "/>    </mappers></configuration> 

We notice that the change is

<mappers> <mapper resource= "Com/xcode/beens/mapperinterfaces/usermapper.xml"/></mappers>

Then we create a new usermapper.xml configuration file under the com.xcode.beens.mapperInterfaces Package

<?xml version= "1.0"  encoding= "UTF-8"  ?> <! doctype mapper     public  "-//mybatis.org//dtd mapper 3.0//en"       "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace = "Com.xcode.beens.mapperInterfaces.UserMapper" >     <cache />     <!--  The Resulttype here is configured to alias in Mybatis-config.xml  -->    < Select id= "Selectuserbyid"  parametertype= "int"  resulttype= "User" >             select * from user where id =  #{id}    </select>        <select  id= "Selectusersbyname"  parametertype= "string"  resultmap= "Resultlistuser" >            select * from user where name = #{name}    </select>     <!--  returnmap -->    <resultmap  defined to return the list  type Type= "User"  id= "Resultlistuser" >        <id column= "id " property=" id " />        <result column=" name "  property= "name"  />        <result column= "Sex"  property= "Sex"  />        <result column= "address "Address"  />    </resultMap>       property=    <insert id= "Insertuser"  parametertype= "User" >            INSERT INTO  ' user '   (' name ',  ' sex ',  ' address ')  VALUES  (#{naMe},#{sex},#{address})     </insert>         <delete id= "Deleteuserbyid"  parametertype= "int" >            delete from user where id = #{id}     </delete>    </mapper>

We note one line:

<mapper namespace= "Com.xcode.beens.mapperInterfaces.UserMapper" >

Namespace is configured with the fully qualified name of the Mapper interface.

And we'll revise Usermapper.java .

Package Com.xcode.beens.mapperinterfaces;import Java.util.list;import Com.xcode.beens.user;public interface Usermapper{public User Selectuserbyid (int id);p ublic list<user> selectusersbyname (String name);p ublic void Insertuser (user user);p ublic void Deleteuserbyid (int id);}

We have deleted all the previous annotations here, and the annotated SQL statement is configured in the Usermapper.xml file.



All right, knock it off! Then execute the previous Main, level two cache use success!

Many of these are not detailed here, such as the mapper configuration file. and the return result set is more than one time, how to convert to list. I have just learned to write a blog just to record it so that I forget later, can quickly pick up.











MyBatis Study Notes (ii) MyBatis caching mechanism

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.