MyBatis lazy loading and caching

First, lazy loading

1. The main object loading:

The concept did not delay, are loaded directly.

2. Load the timing of the associated object:

01. Direct loading:

Access to the main target, but also loaded associated objects

02. invasive delay:

Access to the main object does not load the associated objects

When accessing the main attributes of object properties, associated objects will be loaded

03. depth delay

Access to the main object does not load the associated objects

When accessing the main attributes of the object, the associated object will not be loaded

Access to the associated object or the associated object attributes time, it will load the associated objects.

3. many delay loading code:

01. Entity class code:

package cn.pb.bean;

import java.util.Set;

/**
 * State of the entity class
 * / 
Public  class Country {
     Private Integer cid; // national numbering 
    Private String cName; // name of the country

    // associated capital property 
    Private the Set <Provincial> the provincials;

    public Integer getcId() {
        return cId;
    }

    public void setcId(Integer cId) {
        this.cId = cId;
    }

    public String getcName() {
        return cName;
    }

    public void setcName(String cName) {
        this.cName = cName;
    }

    public Set<Provincial> getProvincials() {
        return provincials;
    }

    public void setProvincials(Set<Provincial> provincials) {
        this.provincials = provincials;
    }

   
}
package cn.pb.bean;

/**
 * Capital corresponding entity class
 * / 
Public  class Provincial {
     Private Integer pId;     // capital number 
    Private String pName;   // capital Name

    public Integer getpId() {
        return pId;
    }
    public void setpId(Integer pId) {
        this.pId = pId;
    }
    public String getpName() {
        return pName;
    }
    public void setpName(String pName) {
        this.pName = pName;
    }
}

02.dao level code:

public interface CountryDao {
/**
 * Query information as well as the national capital following the country in accordance with national id
 */
Country selectCountryById(Integer id);
}    

03.mapper.xml Code:

<mapper namespace="cn.pb.dao.CountryDao">
  <-!. 01 to check out a number of national information according to id sql query can use lazy loading strategies ->
    <select id="selectCountryById" resultMap="countryMap">
        select cid,cname from country where cid=#{xxx}
    </select>
  <-!. 03 provinces in accordance with national id check out the information ->
    <select id="selectProvincialByCountryId" resultType="Provincial">
        select pid,pname from provincial
        countryId WHERE = # {XXX}
         <-! # {XXX} corresponding to the collection node is resultMap following column ->
    </select>

  <-! 02 national mapping information ->
    <resultMap id="countryMap" type="Country">
        <id property="cId" column="cid"/>
        <result property="cName" column="cname"/>
        <! - setting a set of attributes associated
         select: query needs associated
        column: select statement associated with the required parameters ->
        <collection property="provincials" ofType="Provincials"
                    select="selectProvincialByCountryId"
                    column="cid"/>
    </resultMap>

    
</mapper>

04. Test the code:

public class CountryTest {
    DAO CountryDao = null ;
    SqlSession session=null;
    Logger log= Logger.getLogger(CountryTest.class);

    @Before
    public void before(){

        // Get the session 
        the session = SessionFactoryUtil.getSession ();
         // get a class object is performed 
        DAO = session.getMapper (CountryDao. Class );
    }

    /**
     * Operation to be performed after all of the test method for performing tests
     */
    @After
    public void after(){
        if(session!=null){
            session.close();
        }
    }

  <! - only the output of the main load the object will have a sql statement ->
    @Test
    public void testSelectCountryById(){
        Country country=dao.selectCountryById(1);
        log.debug ( "National Information inquiry according to the above mentioned id" + Country);
    }

  
  <! - there will be two sql statements output information associated object ->
    @Test
    public void testSelectCountryById(){
        Country country=dao.selectCountryById(1);
        log.debug ( "id query according to the State Information" + country.getProvincials ());
    }

}

4. Configuration lazy loading:

In mybatis.xml configuration file:

<Settings> 
<-! globally enables or disables lazy loading. When disabled, all associated configuration will be loaded immediately. ->
<Setting name = "lazyLoadingEnabled" value = "to true" />
<-!, When enabled, an object with attributes of any delay loading a delay profile is loaded, the object
of all of the attributes will be loaded . Otherwise, all properties are loaded on demand. Intrusive delay ->
<Setting name = "aggressiveLazyLoading" value = "to false" />
</ Settings>

 

Two, MyBatis cache

1. The role of the query cache:

Query cache used primarily to provide query access speed. The user data query process is repeated for the same simplified, no longer get the results each time the query data from the database, thereby enhancing access speed.

2. With regard to the cache description:

01.MyBatis query caching mechanism. The scope life cycle buffer area, may be divided into two: one cache and level two cache.

02.MyBatis query cache scope is based on namespace partitioning mapping file, the same namespace mapper query data in a cache in the same area. Interfering data at different namespace. Whether it is a cache or secondary cache are stored separately in accordance with the namespace.

03. However, a secondary cache except that, SqlSession once closed, then the data will not be present in SqlSession, i.e. a cache cease to exist. The secondary cache is synchronized with the entire application life cycle, has nothing to do with SqlSession is closed. In other words, a data cache is shared among the same thread (the SqlSession same), while the secondary cache the data is shared between different threads (different SqlSession).

04. cache: HashMap based PerpetualCache the local cache, its life cycle is Session, when the Session flush or close, all of Cache will be cleared in the Session.

And a secondary cache 05. Cache same mechanism, but also using default PerpetualCache, HashMap stored, it is stored in a different scope as Mapper (Namespace), and may be custom storage source, such as Ehcache.

06. For data cache update mechanism, when a certain scope (a cache Session / secondary cache the Namespaces) were C / U / D after operation, all select default under the scope of the cache will be clear.

 

3. cache:

01. prove the existence of the code cache:

001.dao level code:

/**
 * According to information corresponding to the number of students in inquiry
 * Verify the existence of a cache
 */
Student selectStudentById(Integer sId);

002.mapper.xml Code:

<mapper namespace="cn.pb.dao.StudentDao">
    <-! Inquiry designated students with information to verify the presence of a cache ->
    <select id="selectStudentById" resultType="Student">
        select sid,sname from stu where sid=#{xxx}
    </select>
</mapper>

003. test code:

package cn.pb;


import cn.pb.bean.Student;
import cn.pb.dao.StudentDao;
import cn.pb.util.SessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class StudentTest {
    StudentDao dao;
    SqlSession session;
    Logger logger=Logger.getLogger(StudentDao.class);
    @Before
    public void before(){
        session= SessionFactoryUtil.getSession();
        dao=session.getMapper(StudentDao.class);
    }

    /**
     * Operation to be performed after all of the test method for performing tests
     */
    @After
    public void after(){
        if(session!=null){
            session.close();
        }
    }


    /**
     * Verify the existence of a cache
     * MyBatis level cache is always on and can not turn off!
     */
    @Test
    public void test1(){
        Student student=dao.selectStudentById(1);
        logger.debug ( "id for the first time found 1 student:" + Student);
         // query id the same object again 
        Student STUDENT2 = dao.selectStudentById (1 );
        logger.debug ( "2nd student id is found in 1:" + STUDENT2);
    }
}

02. cache - based on data from the cache to find:

001. The cache underlying implementation is a Map, Map of value is the result of the query

002.Map the key, that is based on a query, use different ORM framework, based on different queries

003.MyBatis query based on: Sql's id + SQL statement

004.Hibernate query based on: id query result object

005. validation code:

a.dao level code:

/ ** 
* Verify basis mybatis cache query!
* /
Student selectStudentById2 (sId and Integer);
b.mapper.xml Code:
<mapper namespace="cn.pb.dao.StudentDao">
   
    <-! Query specifies verify student information based on mybatis cache query!
             Id two queries statements are inconsistent, but the same sql statement ->
    <select id="selectStudentById2" resultType="Student">
        select  sid,sname from  stu where sid=#{xxx}
    </select>

   
</mapper>

. C test code:

/**
 * Upon verification of the query
 * Both queries are queries id object 1 for students, but the query statement is inconsistent id
 */

@Test
public void test2() {
    Student student = dao.selectStudentById(1);
    logger.debug ( "1st id is found in 1 of the students:" + Student);
     // query id the same object again 
    Student STUDENT2 = dao.selectStudentById2 (1 );
    logger.debug ( "2nd student id is found in 1:" + STUDENT2);
}
The conclusion is: 
the mybatis query based on: mapper file in the id + sql sql statement!
hibernate based on the underlying query is: query object id!

In fact, the bottom is a cache of the Map,
the Map's key inquiry is based, value is the result of the query!



03. add, delete, change impact on a cache:

Additions and deletions will empty the cache: Note: You must insert labels, you can not use select, or experiments do not succeed

001.dao level code:

/**
 * Verify additions and deletions affect change check a cache!
 */
void addStudent(Student student);

 

Guess you like

Origin www.cnblogs.com/cw172/p/11682226.html