hibernate 的N + 1问题


一、           定义:

首先发出一条语句查询当前对象,然后发出N条语句查询关联对象,N不确定,效率比较低。

 

 

两张表的数据

在查询category表的时候,查询相应的管理员

hibernate 会发送三条数据,

一条用于查询category表中的数据,

根据id,另两条用于查询级联的账户表,查到的将不再查询。

 

Hibernate: select category0_.id asid0_, category0_.type as type0_, category0_.hot as hot0_, category0_.aid asaid0_ from shop.category category0_ where category0_.type like ?

用于查询账户1和账户2:

Hibernate: select account0_.id asid1_0_, account0_.login as login1_0_, account0_.name as name1_0_,account0_.pass as pass1_0_ from shop.account account0_ where account0_.id=?

 

Hibernate: select account0_.id asid1_0_, account0_.login as login1_0_, account0_.name as name1_0_,account0_.pass as pass1_0_ from shop.account account0_ where account0_.id=?

 

如果 有A-->B-->C的关联关系,会发很多的sql语句

 

二、           hibernate解决方案:

 <!-- lazy=false级联查询关联对象

          N+1:首先发出一条语句查询当前对象,然后发出语句查询关联对象,N不确定,因此效率相对较低

          fetch:什么样的方式加载关联对象,可以选择select(默认)join多表查询

          注意:在many-to-one:的情况下:join是无效的

         

          -->

        <many-to-onename="account"class="Account"lazy="false" fetch="join">

        <columnname="aid"/>

       </many-to-one>

三、           我们的解决方案:

自己写HQL语句取代基于XML的配置,则可以提升性能,

xml中只需要如下配置,不需要懒加载 lazy="false"fetch="join",否则性能上不来

<many-to-onename="account"class="Account">

        <columnname="aid"/>

</many-to-one>

 

sql语句如下:注意这里不需要On,On语法是错误的,对应的id关系已经在xml中配置了

 

木有fetch,查询的是object【】数组

List<Category> list=getSession().createQuery("FROM Category c  LEFT JOIN  c.account   WHERE c.type like :type")

                .setString("type","%" + type + "%")

                .list();

 

有fetch将把aount对象中的属性抓取出来放入category对象的account属性中

List<Category> list=getSession().createQuery("FROM Category c  LEFT JOIN  fetch c.account WHEREc.type like :type")

                .setString("type","%" + type + "%")

                .list();        

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

q1054261752

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值