mybatis03
延迟加载策略(关联查询)
延迟加载的简介
-
延时加载
- 延迟加载(lazy load 也称懒加载)是关联关系对象默认的加载方式,延迟加载机制就是当在真正需要数据的时候,才真正执行数据加载操作
- 延迟加载,可以简单理解为,只有在使用的时候,才会发出sql语句进行查询
-
为什么使用延迟加载
- 减少访问数据库的频率,要访问的数据量过大时,明显用缓存不太合适,因为内存容量有限为了减少并发量,减少系统资源的消耗
局部延时加载
-
映射配置文件
<select id="getDepartmentById" resultMap="DepartemntResultMap"> select * from department where d_id=#{id} </select> <resultMap id="DepartemntResultMap" type="Department"> <id column="d_id" property="id"></id> <result column="d_name" property="name"></result> <collection property="emps" ofType="Employee" column="d_id" select="cn.offcn.mapper.EmployeeMapper.getEmployeeByDepartId" fetchType=”lazy”> </collection> </resultMap> 相关联的查询标签上加 fetchType=”lazy” fetchType默认值为eager 立即加载,Lazy为延时加载。
全局延时加载
- 如果希望所有关联都需要延时加载,可以在mybatis的核心配置文件中进行配置,不用在collection或association中指定。默认全局开启。
<settings> <!--开启延时加载开关--> <setting name="lazyLoadingEnabled" value="true"/> <!--关闭立即加载,实施按需加载--> <setting name="aggressiveLazyLoading" value="false"/> </settings>
MyBatis的逆向工程(代码生成器)
逆向工厂介绍
- 正向工程:Object---->自动生成数据库的表(hibernate)
- MyBatis的一个主要的特点就是需要程序员自己编写sql,那么如果表太多的话,难免会很麻烦,所以mybatis官方提供了一个逆向工程,可以针对单表自动生成mybatis执行所需要的代码(包括mapper.xml、mapper.java、po..)。一般在开发中,常用的逆向工程方式是通过数据库的表生成代码。
- mybatis逆向工程:表---->接口(方法 单表的CRUD)
正向工程:hibernate Customer Car----自动生成表
构建项目环境
- 构建maven工程并导入依赖
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.7</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> </dependencies>
- 编写配置框架配置文件
?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> <properties resource="db.properties"></properties> <settings> <setting name="lazyLoadingEnabled" value="true"/> <!--开启二级缓存--> <setting name="cacheEnabled" value="true"/> </settings> <typeAliases> <package name="cn.offcn.entity"></package> </typeAliases> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin> </plugins> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <!--在核心配置文件中注册mapper--> <mappers> <package name="cn.offcn.mapper"></package> </mappers> </configuration>
- 编写逆向工程的配置文件generator.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="testTables" targetRuntime="MyBatis3"> <commentGenerator> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--数据库连接的信息:驱动类、连接地址、用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mybatis828_002" userId="root" password="root"> </jdbcConnection> <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- targetProject:生成实体类的位置 --> <javaModelGenerator targetPackage="cn.offcn.entity" targetProject=".\src\main\java"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" /> <!-- 从数据库返回的值被清理前后的空格 --> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- targetProject:mapper映射文件生成的位置 --> <sqlMapGenerator targetPackage="cn.offcn.mapper" targetProject=".\src\main\java"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!-- targetPackage:mapper接口生成的位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="cn.offcn.mapper" targetProject=".\src\main\java"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!-- 指定数据库表 --> <table tableName="department"></table> <table tableName="employee"></table> <table tableName="person"></table> <table tableName="idcard"></table> <table tableName="student"></table> <table tableName="teacher_student"></table> <table tableName="teacher"></table> </context> </generatorConfiguration>
- 调用官方api实现逆向工程
package cn.test; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.internal.DefaultShellCallback; import java.io.File; import java.util.ArrayList; import java.util.List; public class GeneratorTest { public static void main(String[] args) throws Exception{ List<String> warnings = new ArrayList<String>(); boolean overwrite = true; //指定 逆向工程配置文件 File configFile = new File("F:\\828class\\workspace\\mybatis\\mybatis004_reflect\\generatorConfig.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callba ck = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); } }
MyBatis缓存
缓存简介
- 缓存是存在于内存中的临时数据,使用缓存的目的是减少和数据库的交互次数,提高执行效率。像大多数的持久化框架一样,Mybatis 也提供了缓存策略,通过缓存策略来减少数据库的查询次数,从而提高性能,Mybatis 中缓存分为一级缓存,二级缓存。
一级缓存
-
一级缓存介绍
- mybatis一级缓存一种是SESSION级别的,针对同一个会话SqlSession中,执行多次条件完全相同的同一个sql,那么会共享这一缓存。
-
一级缓存分析
- 写了两次查询操作,但在访问数据时,只有一次。第一次先从一级缓存中获取,因为session是新创建的,一级缓存中没有数据,于是就查询数据获取数据,然后把查询的数据放到一级缓存中,此时一定要注意的是,一级缓存是一个Map集合,map的key是你的查询条件字符串,值就是查询出来的对象。等第二次查询时,先从一缓存中获取,因为上一次查询后已经放到一级缓存中了,所以从一级缓存中获取到了,就不用访问数据库了,减少和数据次的一次交互,提高了执行效率。
二级缓存
-
二级缓存介绍
- 二级缓存是 mapper 映射级别的缓存,多个 SqlSession 去操作同一个 Mapper 映射的 sql 语句,多个SqlSession 可以共用二级缓存,二级缓存是跨 SqlSession 的。
-
二级缓存开启与关闭
在SqlMapConfig.xml 文件开启二级缓存
<settings> <!-- 开启二级缓存的支持 --> <setting name="cacheEnabled" value="true"/> </settings> 因为 cacheEnabled 的取值默认就为 true,所以这一步可以省略不配置。为 true 代表开启二级缓存;为 false 代表不开启二级缓存。配置相关的 Mapper 映射文件
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.offcn.dao.EmployeeDao"> <!-- 开启二级缓存的支持 --> <cache></cache> </mapper>配置 statement 上面的 useCache 属性
<select id="getEmployeeById" resultMap="EmployeeResultMap" useCache="true"> SELECT * FROM employee WHERE e_id=#{id} </select> <resultMap id="EmployeeResultMap" type="Employee"> <id column="e_id" property="id"></id> <result column="e_name" property="name"></result> <result column="e_gender" property="gender"></result> <result column="e_age" property="age"></result> </resultMap> 将 EmployeeDao.xml 映射文件中的<select>标签中设置 useCache=”true”代表当前这个 statement 要使用二级缓存,如果不使用二级缓存可以设置为 false。 注意:针对每次查询都需要最新的数据 sql,要设置成 useCache=false,禁用二级缓存。
MyBatis分页插件
分页插件介绍
-
分页是一种将所有数据分段展示给用户的技术.用户每次看到的不是全部数据,而是其中的一部分,如果在其中没有找到自己想要的内容,用户可以通过制定页码或是翻页的方式转换可见内容,直到找到自己想要的内容为止。
-
分页的好处
- 提高性能
另外如果数据量很大,一次性将内容都查询出来,查询出来的结果是放在内存存里面的,会增加cpu的开销造成内存的浪费,效率极低。 - 数据太多不易排版
- 提高性能
分页插件的引入和配置
1.在pom.xml中引入插件依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.10</version>
</dependency>
2.在mybatis核心配置文件中进行配置
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>

浙公网安备 33010602011771号