当前位置 博文首页 > 文章内容

    java工程师进阶之MyBatis延迟加载的使用

    作者:shunshunshun18 栏目:未分类 时间:2021-09-15 14:42:51

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



    什么是延迟加载?

    延迟加载也叫懒加载、惰性加载,使⽤延迟加载可以提⾼程序的运行效率,针对于数据持久层的操作, 在某些特定的情况下去访问特定的数据库,在其他情况下可以不访问某些表,从⼀定程度上减少了 Java 应⽤与数据库的交互次数。

    查询学⽣和班级的时,学生和班级是两张不同的表,如果当前需求只需要获取学shengsheng的信息,那么查询学 ⽣单表即可,如果需要通过学⽣获取对应的班级信息,则必须查询两张表。 不同的业务需求,需要查询不同的表,根据具体的业务需求来动态减少数据表查询的⼯作就是延迟加载。

    如何使用延迟加载?

    1.在 config.xml 中开启延迟加载

    <settings>
     <!-- 打印SQL-->
     <setting name="logImpl" value="STDOUT_LOGGING" />
     <!-- 开启延迟加载 -->
     <setting name="lazyLoadingEnabled" value="true"/>
    </settings>

    2.将多表关联查询拆分成多个单表查询

    StudentRepository中

     public Student findByIdLazy(long id);

    StudentRepository.xml

    <resultMap id="studentMapLazy" type="entity.Student">
            <id column="id" property="id"></id>
            <result column="name" property="name"></result>
            <association property="classes" javaType="entity.Classes" select="repository.ClassesRepository.findByIdLazy" column="cld">
            </association>
        </resultMap>
        <select id="findByIdLazy" parameterType="long" resultMap="studentMapLazy">
    -- select s.id ,s.name,c.id as cid,c.name as cname from student s,classes c where s.id =1 and s.cld=c.id;
        select * from student where id=#{id};
        </select>

    ClassesRepository

    public Classes findByIdLazy(long id);
    <resultMap id="classesMap" type="entity.Classes">
            <id column="cid" property="id"></id>
            <result column="cname" property="name"></result>
            <collection property="students" ofType="entity.Student">
                <id column="id" property="id"></id>
                <result column="name" property="name"></result>
            </collection>
        </resultMap>

    以上就是java工程师进阶之MyBatis延迟加载的使用的详细内容,更多关于java之MyBatis延迟加载的资料请关注IIS7站长之家博文其它相关文章!