Mybatis延迟加载

Source

延迟加载需要先在核心配置文件(sqlmapconfig.xml)中设置延迟开关和按需加载

		<!-- 延迟加载开关 -->
		<setting name="lazyLoadingEnabled" value="true" />
		<!-- 设置按需加载 -->
		<setting name="aggressiveLazyLoading" value="false" />

		<!-- 打印日志 -->
		<setting name="logImpl" value="STDOUT_LOGGING" />

一对一表关系延迟加载 demo

创建好实体类 UserBean 和 RoleBean 并且设置好对应的get和set方法

//UserBean 实体类下 记得设置对应的get和set方法
	private int uid;
	private String loginName;
	private String ps;
	private String email;
	private int ztStatic;
	private int deleteZt;
	private String userName;
	private RoleBean role;

//RoleBean 实体类下 记得设置对应的get和set方法
	private int roleId;
	private String roleName;
	private int ztStatic;
	private int deleteZt;

text → service → dao → mapper
mapper文件中的配置和SQL语句:

//头文件
<?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">

//多表关系的返回类型需要用到resultMap类型
<mapper namespace="dao.UserDao"> //这个namespace命名需要对应dao层接口名称
	<resultMap type="bean.UserBean" id="user_roleYC">
		<id column="uid" property="uid"/>
		<result column="loginName" property="loginName"/>
		<result column="ps" property="ps"/>
		<result column="email" property="email"/>
		<result column="ztStatic" property="ztStatic"/>
		<result column="deleteZt" property="deleteZt"/>
		<result column="userName" property="userName"/>
		//这是在加载id为getRYC的sql语句,这样的sql语句拼接就不会造成笛卡尔积现象发生
		<association property="role" javaType="bean.RoleBean" select="getRYC" column="roleId"></association>
	</resultMap>
	
	<select id="getURYC" parameterType="int" resultMap="user_roleYC">
		select * from usertable where uid = #{uid}
	</select>
	<select id="getRYC" parameterType="int" resultType="bean.RoleBean">
		select * from role where roleId = #{roleId}
	</select>

</mapper>
发布了13 篇原创文章 · 获赞 0 · 访问量 216