懒加载机制

懒加载机制

Mybatis懒加载机制比hibernate来的简单.只对关联查询时,会使用懒加载.

1.懒加载前提

1.关联查询时,要使用select方式进行查询,不能使用join查询
2.默认情况,mybatis没有开启懒加载,所以要在Config文件配置全局设置

原理:
当需要加载关联表数据时,mybatis会为你查询关联表,否则,不去查询关联表,提交服务器的性能.

2.代码示例

mybatis-config.xml文件配置

<?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>
    <settings>
        <setting name="lazyLoadingEnabled" value="true"/>
    </settings>
   
    <!--省略其他配置-->
</configuration>
<!--OrdersMapper.xml-->
<?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">

<mapper namespace="mapper.OrdersMapper">

    <resultMap id="baseResultMap2" type="Orders">
        <id property="id" column="ID"></id>
        <result property="price" column="PRICE"></result>
        <association property="user" javaType="User" column="UID" select="mapper.UserMapper.selectById"></association>
    </resultMap>

    <!--方式二:通过select语句方式-->
    <select id="selectById2" parameterType="java.lang.Integer" resultMap="baseResultMap2">
        select * from orders where id = #{id}
    </select>

</mapper>
<!--UserMapper.xml-->
<?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">

<mapper namespace="mapper.UserMapper">
    
     <resultMap id="baseResultMap" type="User">
        <id column="ID" property="id"></id>
        <result column="NAME" property="username"></result>
        <result column="PASSWORD" property="password"></result>
    </resultMap>
  
    <select id="selectById"  resultMap="baseResultMap">
        select * from user where id = #{id}
    </select>
</mapper>
//OrdersMapper接口
public interface OrdersMapper {

    Orders selectById2(int id);

}

//OrdersService
public class OrdersService {

    public Orders findById2(int id){

        SqlSession session = DBUtil.openSqlSession();

        OrdersMapper mapper = session.getMapper(OrdersMapper.class);

        Orders orders = mapper.selectById2(id);

        session.close();

        return orders;
    }
}
//测试类
   @Test
    public void testFindById2(){
		//当没有主动使用关联数据时,会发现没有使用select语句去查询关联表,只有使用的时候才去查询
        Orders orders = service.findById2(1);
        
        System.out.println(orders.getUser());
     
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值