斩秋 2008-12-03 22:50
浏览 281
已采纳

一对多双向关联,级联删除,sql语句优化问题

父类
public class Item {
private long itemId;
private String name;
private Set subItem = new HashSet();
...................
}

        <class name="Item" >
    <id name="itemId">
        <generator class="native"/>
    </id>
    <property name="name"></property>

    <set name="subItem" inverse="true" cascade="save-update,delete" >
        <key column="item_id"></key>
        <one-to-many class="SubItem"/>
    </set>  
        </class>

子类

public class SubItem {
private long subItemId;
private String subItemName;
private Item item;
...................
}

<class name="SubItem" >
    <id name="subItemId">
        <generator class="native"/>
    </id>
    <property name="subItemName"></property>    
    <many-to-one name="item" column="item_id"></many-to-one>        
</class>

级联删除
session.beginTransaction();
Item item = (Item) session.load(Item.class, new Long(2));
session.delete(item);
session.getTransaction().commit();

生成的sql语句

Hibernate: select item0_.itemId as itemId0_0_, item0_.name as name0_0_ from Item item0_ where item0_.itemId=?
Hibernate: select subitem0_.item_id as item3_1_, subitem0_.subItemId as subItemId1_, subitem0_.subItemId as subItemId1_0_, subitem0_.subItemName as subItemN2_1_0_, subitem0_.item_id as item3_1_0_ from SubItem subitem0_ where subitem0_.item_id=?
[size=large][b]Hibernate: delete from SubItem where subItemId=?
Hibernate: delete from SubItem where subItemId=?
Hibernate: delete from SubItem where subItemId=?
Hibernate: delete from SubItem where subItemId=?[/b][/size]
Hibernate: delete from Item where itemId=?

其中加粗部分 显然是低效率的 如果字表有1000条语句的匹配的话就要1000条delete语句
其实一条就可以了 delete from SubItem where item_id=?
在hibernate中如何做到

  • 写回答

1条回答 默认 最新

  • iteye_10167 2008-12-03 23:23
    关注

    不知道具体您的数据量有多少?

    系统的优化需要考虑很多方面,虽然采用类似in (...)来处理,就着一次执行来说,性能有一定的提高。但如果DB是Oracle(其他DB也应该类似),delete from SubItem where subItemId=?会对这样的语句做缓存,而in(...)很难有效缓存,并且甚至,如果in(...)的内容过多sql过大,会导致DB性能严重下降,直至崩溃。
    所以,如果你的items数量不是很大(平均 < 1000),没有必要优化。

    如果确实数量很大,建议直接使用sql来删除,例如你这里可以考虑使用
    delete from SubItem where Item_Id=? 删除。或者通过存储过程来优化。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?