Delayed loading in mybatis and delayed loading in mybatis

Source: Internet
Author: User

Delayed loading in mybatis and delayed loading in mybatis
I. Delayed Loading

ResultMap can implement advanced ing (one-to-one and one-to-many ing using association and collection). association and collection have the delayed loading function.

Delayed loading: queries from a single table are performed first and associated tables are queried when necessary, which greatly improves database performance because querying a single table is faster than querying multiple associated tables.

Configure in the mybatis core configuration file:

LazyLoadingEnabled, aggressiveLazyLoading

Settings

Description

Allowed value

Default Value

LazyLoadingEnabled

Global settings are lazy. If it is set to 'false', all associated objects will be initialized and loaded.

True | false

False

AggressiveLazyLoading

When it is set to 'true', the lazy objects may be loaded by all lazy attributes. Otherwise, each attribute is loaded as needed.

True | false

True

<settings>      <setting name="lazyLoadingEnabled" value="true"/>      <setting name="aggressiveLazyLoading" value="false"/></settings>

Occasion:

When only some records need to be associated with other information for query, loading can be delayed as needed, and SQL is sent to the database when associated query is required to improve database performance.

When all associated query information is required, you can directly return all associated query information without delay loading. You can use resultType or resultMap to complete the ing.

Ii. Case study: (one-to-multiple employees in the Department)

Source code introduction:

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;/*** tool class **/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); // provides a method for obtaining the 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 {/*** query the specified record * @ return * @ throws IOException */public Dept findById (Integer id) throws IOException ;}
View Code

5. DeptDAO. xml

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapperPUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <mapper namespace =" cn. zhang. dao. DeptDao "> <! -- 3. query employee information by employee id --> <select id = "selectEmpByDeptNo" resultType = "Emp"> select empno, empname from emp where deptno =#{ deptno} </select> <! -- 2. ing to department entities --> <resultMap type = "Dept" id = "deptMapper"> <id property = "deptno" column = "deptno"/> <result property = "deptname "column =" deptname "/> <! -- An employee associated with multiple departments --> <! -- Select: Query associated employees --> <! -- Column: conditions required for association employee query (from 1) --> <collection property = "emp" ofType = "Emp" select = "selectEmpByDeptNo" column = "deptno"/> </resultMap> <! -- 1. query department information by Department id --> <select id = "findById" resultMap = "deptMapper"> select deptno, deptname from dept where deptno =#{ deptno} </select> </mapper>
View Code

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

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE configurationPUBLIC "-// mybatis.org//DTD Config 3.0 //" http://mybatis.org/dtd/mybatis-3-config.dtd "> <configuration> <! -- LazyLoadingEnabled: sets the lazy loading. The default value is false. If it is false, all associated objects will be initialized and loaded. AggressiveLazyLoading: The default value is true. If this parameter is set to true, the objects to be loaded by any lazy attribute may be loaded. Otherwise, each attribute is loaded as needed. --> <Settings> <! -- Enable delayed loading --> <setting name = "lazyLoadingEnabled" value = "true"/> <! -- Change the active loading to message loading as needed --> <setting name = "aggressiveLazyLoading" value = "false"/> </settings> <! -- Configure the alias --> <typeAliases> <! -- Method 1: Customize aliases by type name --> <! -- Method 2: Use the simple class name under the current specified package as the alias --> <package name = "cn. zhang. entity "/> </typeAliases> <environments default =" oracle "> <environment id =" oracle "> <! -- Use jdbc transactions --> <transactionManager type = "JDBC"/> <! -- Use the built-in connection pool --> <dataSource type = "POOLED"> <! -- My Oracle database --> <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>
View Code

7. MyTest. java (test class)

Package cn. zhang. test; // One-to-multiple 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);}/*** query the specified record * @ throws IOException */@ Test public void findAll () throws IOException {Dept dept = dao. findById (1); System. out. println (dept );}}
View Code Test Result:

Place a breakpoint at the following position

Case 1: No configuration in mybatis-config.xml

Scenario 2: Configure in mybatis-config.xml

<Settings> <! -- Enable delayed loading --> <setting name = "lazyLoadingEnabled" value = "true"/> <! -- Change the active loading to message loading as needed --> <setting name = "aggressiveLazyLoading" value = "false"/> </settings>

Next step:

Next step of F6:

Step 6: Name the employee

Case 3:

F6 next step:

 

F6 next step: print the employee name

 

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.