問題出現
由於多表查詢相對於單表查詢是非常消耗時間的,所以就出現了延遲加載的方法,首先延遲加載,先從單表開始查詢,在查詢對應多表的數據,單表查詢速度比多表查詢塊,所以延遲加載是可以提升數據查詢速度。
延遲加載的實現
使用resultMap實現高級映射,也就是使用association或者collection
實現延遲加載需要開啓mybatis延遲加載的開關,和關閉積極加載(也就是按需加載)
lazyLoadingEnable:延遲加載開關,默認關閉,所以想要延遲加載必須開啓。
aggressiveLazyLoading:積極加載,默認開啓,所以需要關閉,關閉後就是按需求來進行加載。
Mybatis配置文件加入
<settings>
<!-- 打開延遲加載開關 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 關閉積極加載,就是按需加載 -->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
代碼實例
UserVo.java就是我們需要獲取的user信息和food信息,直接查詢必然會出現多表查詢
這裏我們具體實現就是先加載user信息,而food信息進行延遲加載
package com.my.shiro.Entity;
public class UserVo {
private static final long serialVersionUID = 1L;
private String username;
private String password;
private String permission;
private Food food;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
public Food getFood() {
return food;
}
public void setFood(Food food) {
this.food = food;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
UserMapper.xml resultMap實現延遲加載需要的配置
<resultMap id="LazyLoading" type="com.my.shiro.Entity.UserVo" >
<id column="username" property="username" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="permission" property="permission" jdbcType="VARCHAR" />
<!-- 用於延遲加載
select中的statement的id:比如findpassword,如果不在同一個mapper中就應該加上全限定名
colum關聯信息 -->
<association property="food" javaType="com.my.shiro.Entity.Food"
select="com.my.shiro.Dao.FoodMapper.findFoodByUsername"
column="username">
</association>
<!-- <collection property=""></collection> -->
</resultMap>
這裏使用association實現延遲加載這裏主要有4的屬性
property:這裏的這個屬性對應的是UserVo中的food
javaType:延遲加載數據類型
select:延遲加載需要使用的方法對應的statement的id也就一個sql方法對應的id,這裏需要注意的是如果這個sql不再該mapper.xml中那麼需要加上這個sql的namespace
colum:關聯信息,也就是我們通常多表關聯的信息
resultMap的使用
<select id="findUserAndFood" resultMap="LazyLoading">
select * from user;
</select>
這裏先會執行select * from user 查詢到信息,再通過resultMap中配置的association來執行findFoodByUsername對應的sql,從而實現延遲加載findFoodByUsername
<select id="findFoodByUsername" parameterType="java.lang.String" resultType="com.my.shiro.Entity.Food">
select *
from food
where username = #{username}
</select>
這裏的parameter可以看做resultMap中的association中的colum對應的值,也就是關聯屬性
在這裏我遇到一個問題就是當parametreType爲sting的時候不可以寫成下面的格式
<where>
<if test="username != null and username != ''">
and username = #{username}
</if>
</where>
其實上面sql可以看作,這裏避免了多表之間的查詢
select username,password,
(select price from food where username = user.username)price,
(select name from food where username = user.username)name
from user
至於collection使用法大體上是相似的