In layman's language Mybatis series (ten) lazy loading ---

First, lazy loading

  resultMap can implement advanced mapping (using the association, collection and achieve one-to-many mapping), association, collection with lazy loading function.

  Lazy loading: start with the single-table query, and then go from the association table associated with the query when needed, greatly improving database performance, because the single-table queries related query multiple tables than faster.

In mybatis core configuration file is:

Settings

description

allowance

Defaults

lazyLoadingEnabled

Global settings lazy loading. If set to 'false', all the associated load will be initialized.

true | false

false

aggressiveLazyLoading

When set to 'true' when the object may be any lazy loading all lazy loading property. Otherwise, each attribute are loaded on demand.

true | false

true

<settings>

      <setting name="lazyLoadingEnabled" value="true"/>

      <setting name="aggressiveLazyLoading" value="false"/>

</settings>

occasion:

         When only a portion of the recording need additional information associated with the query, this time delay may be loaded on demand, when needed issued sql relational query the database again to increase database performance.

         When all required information related query, then do not delay loading, query information directly related to the return of all, you can use resultType or resultMap complete the mapping.

II: Case :( in many departments and employees)

1.Dept.java

package cn.zhang.entity;

import java.util.HashSet;
import java.util.Set;

public class Dept {
    
    private Integer deptno;

    private String deptname;

    private Set<Emp> emp = new HashSet<Emp>();
    

    @Override
    public String toString() {
        return "Dept [deptno=" + deptno + ", deptname=" + deptname + ", emp="
                + emp + "]";
    }

    public Integer getDeptno() {
        return deptno;
    }

    public void setDeptno(Integer deptno) {
        this.deptno = deptno;
    }

    public String getDeptname() {
        return deptname;
    }

    public void setDeptname(String deptname) {
        this.deptname = deptname;
    }

    public Set<Emp> getEmp() {
        return emp;
    }

    public void setEmp(Set<Emp> emp) {
        this.emp = emp;
    }

}
View Code

2.Emp.java

package cn.zhang.entity;

public class Emp {
    
    private Integer empno;
    
    private String empname;
    

    @Override
    public String toString() {
        return "Emp [empno=" + empno + ", empname=" + empname + "]";
    }

    public Integer getEmpno() {
        return empno;
    }

    public void setEmpno(Integer empno) {
        this.empno = empno;
    }

    public String getEmpname() {
        return empname;
    }

    public void setEmpname(String empname) {
        this.empname = empname;
    }


    

}
View Code

3.MybatisUtil.java

package cn.zhang.util;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * 工具类
 * 
 */
public class MybatisUtil {

    private static String config = "mybatis-config.xml";
    static Reader reader;
    static {
        try {
            reader = Resources.getResourceAsReader(config);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static SqlSessionFactory factory = new SqlSessionFactoryBuilder()
            .build(reader);

    // 提供一个可以获取到session的方法
    public static SqlSession getSession() throws IOException {

        SqlSession session = factory.openSession();
        return session;
    }
}
View Code

4.DeptDao.java

package cn.zhang.dao;

import java.io.IOException;
import cn.zhang.entity.Dept;

public interface DeptDao {

    /**
     * 查询指定记录
     * @return
     * @throws IOException
     */
    public Dept findById(Integer id) throws IOException;


}
View Code

5.DeptDAO.xml

<? Xml Version = "1.0" encoding = "UTF-8" ?> 
<! DOCTYPE Mapper 
the PUBLIC "- // mybatis.org//DTD Mapper 3.0 // EN" 
"http://mybatis.org/dtd/mybatis mapper.dtd--3 " > 
< Mapper namespace =" cn.zhang.dao.DeptDao " > 
    <-! 3. query employee information based on the employee the above mentioned id -> 
    < the SELECT the above mentioned id =" selectEmpByDeptNo " resultType =" Emp " > 
        EMPNO SELECT, EmpName 
        from EMP WHERE DEPTNO DEPTNO = # {} 
    </ SELECT > 
    <-! mapping sector entities 2. -> 
    <resultMap type="Dept" id= "deptMapper" > 
        < the above mentioned id Property = "deptno" column = "deptno"  /> 
        < the Result Property = "deptname" column = "deptname"  /> 
        <-! many department employees association -> 
        <! - - the SELECT: association staff to make inquiries -> 
        <-! column: conditions associated with employee queries required (from 1) -> 
        < Collection Property = "emp" ofType = "emp" the SELECT = "selectEmpByDeptNo" 
            column = " DEPTNO "  /> 
    </ ResultMap > 
    <-! 1. According to the information department id Query department ->
    <select id="findById" resultMap="deptMapper">
        select deptno,deptname from dept
        where deptno=#{deptno}
    </select>

</mapper>

6.mybatis-config.xml (lazy loading configuration here)

<? Xml Version = "1.0" encoding = "UTF-8" ?> 
<! DOCTYPE the Configuration 
the PUBLIC "- // mybatis.org//DTD Config 3.0 // EN" 
"http://mybatis.org/dtd/mybatis config.dtd--3 " > 
< the Configuration > 
    <-! lazyLoadingEnabled: setting lazy loading, default is false. If it is false: all associated will be loaded initialized. 
     aggressiveLazyLoading: The default is true. When set to true, the object may be any lazy lazy loaded property fully loaded; otherwise, each property loaded on demand. -> 
    < Settings > 
        <-! Switch on delay loading -> 
        < Setting name = "lazyLoadingEnabled" value = "to true"  /> 
        <!
        name = "aggressiveLazyLoading" value = "to false"  /> 
    </ Settings > 
    <-! Configure alias -> 
    < typeAliases > 
        <-! way: by custom type name alias -> 
        ! <- Second way: take the simple names of the current packet as specified alias -> 
        < package name = "cn.zhang.entity"  /> 
    </ typeAliases > 
    < Environments default = "Oracle" > 

        < Environment ID = "Oracle" > 
            <! - - use jdbc transaction -> 
            <transactionManager type="JDBC" />
            <!-- 使用自带的连接池 -->
            <dataSource type="POOLED">
                <!-- 我用的Oracle数据库 -->
                <property name="driver" value="oracle.jdbc.driver.OracleDriver" />
                <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
                <property name="username" value="study" />
                <property name="password" value="123" />
            </dataSource>
        </environment>

    </environments>
    <mappers>
        <mapper resource="cn/zhang/dao/DeptDAO.xml" />
    </mappers>
</configuration>

7.MyTest.java (test class)

package cn.zhang.test;
//一对多
import java.io.IOException;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;
import cn.zhang.dao.DeptDao;
import cn.zhang.entity.Dept;
import cn.zhang.util.MybatisUtil;

public class MyTest {
    
    DeptDao dao;
    @Before
    public void initData() throws IOException{
        SqlSession session = MybatisUtil.getSession();
        dao = session.getMapper(DeptDao.class);
    }
    
    
    /**
     * 查询指定记录
     * @throws IOException
     */
    @Test
    public void findAll() throws IOException{
        
        Dept dept = dao.findById(1);
        System.out.println(dept);
        
    }
}
View Code

 

Guess you like

Origin www.cnblogs.com/deityjian/p/11087033.html