---
title: "Restrictions.in查询,及property lazy"
author: "east_java"
date: "2008-11-17T20:26:38Z"
tags: []
slug: "restrictions-in-property-lazy"
draft: false
lastmod: "2008-11-17T20:26:38Z"
id: 269078
url: "https://japi.iteye.com/blog/269078"
---

最近使用Restrictions.in查询发现性能很差.

发现原因有两:
1.sql中,in,not in的运行效率就不是很高.一般使用exits替代.
但是in比exists的效率差也不是绝对的.
http://www.cnblogs.com/zwl12549/archive/2007/04/19/720028.html
http://blog.csdn.net/qustwmt/archive/2008/03/17/2190811.aspx

> IN适合于外表大而内表小的情况；EXISTS适合于外表小而内表大的情况。
> 


> 查询效率分析：
> 子查询为确保消除重复值，必须为外部查询的每个结果都处理嵌套查询。在这种情况下可以考虑用联接查询来取代。
> 
> 如果要用子查询，那就用EXISTS替代IN、用NOT EXISTS替代NOT IN。因为EXISTS引入的子查询只是测试是否存在符合子查询中指定条件的行，效率较高。无论在哪种情况下,NOT IN都是最低效的。因为它对子查询中的表执行了一个全表遍历。
> 
> 建立合理的索引,避免扫描多余数据，避免表扫描！
> 几百万条数据，照样几十毫秒完成查询 
> 


2.发现使用Restrictions.in,不进行二级缓存.
用SQL方式替代此HQL,缓存正常.

----------------------------------------------------------------------

在Hibernate3中添加了property的lazy功能.
一直以为只要设置了lazy=true就能延迟加载.但事实也不是.

在Hibernate Reference中也写到了

> To enable lazy property loading, set the lazy attribute on your particular property mappings: 
> 
> <class name="Document">
>        <id name="id">
>         <generator class="native"/>
>     </id>
>     <property name="name" not-null="true" length="50"/>
>     <property name="summary" not-null="true" length="200" lazy="true"/>
>     <property name="text" not-null="true" length="2000" lazy="true"/>
> </class>
> [color=red]Lazy property loading requires buildtime bytecode instrumentation![/color] If your persistent classes are not enhanced, Hibernate will silently ignore lazy property settings and fall back to immediate fetching. 
> 
> For bytecode instrumentation, use the following Ant task: 
> 
> <target name="instrument" depends="compile">
>     <taskdef name="instrument" classname="org.hibernate.tool.instrument.InstrumentTask">
>         <classpath path="${jar.path}"/>
>         <classpath path="${classes.dir}"/>
>         <classpath refid="lib.class.path"/>
>     </taskdef>
> 
>     <instrument verbose="true">
>         <fileset dir="${testclasses.dir}/org/hibernate/auction/model">
>             <include name="*.class"/>
>         </fileset>
>     </instrument>
> </target>
> A different (better?) way to avoid unnecessary column reads, at least for read-only transactions is to use the projection features of HQL or Criteria queries. This avoids the need for buildtime bytecode processing and is certainly a prefered solution. 
> 


不是很明白<span style="color:darkred">bytecode instrumentation</span>是什么意思.
只能按照<深入浅出Hibernate>中的方法,显示多态的方法实现...