`
awtqty_zhang
  • 浏览: 90700 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Hibernate 之 Hibernate.initialize(Obj)方法 ---减少数据查询时间

 
阅读更多
在当前项目中遇到一个问题,在查询列表时很慢,通过查找,发现在数据查询时耗费太多时间,因为在查询语句中存在left join fetch,需要的关联查询太多,这样查询时,疑Hibernate是将所有数据查询到内存中后,再进行分页的(这就是网上所讲的fetch产生的假分页问题),所以比较慢,后使用Hibernate.initialize(Obj.getXxx())方法后解决该问题。
修改前查询列表功能代码如下:
@SuppressWarnings ("unchecked" )
    public List<TCustomer> findList( boolean status, TUser user, String name, String code, String ledger, int pageNo, int pageSize)
            throws Exception {
        StringBuffer sb = new StringBuffer ();
        HashMap<String, Object> map = new HashMap<String, Object>();
        sb.append( "select distinct customer from TCustomer as customer left join fetch customer.TCustomerLedgers");
        if (status) {
            sb.append( " where customer.id in( select uc.TCustomer.id from TReUserCustomer as uc where uc.TUser =:user) ");
        } else {
            sb.append( " where customer.id not in( select uc.TCustomer.id from TReUserCustomer as uc where uc.TUser =:user) ");
        }
        map.put( "user" , user);
        converQuerySQL(sb, name, code, ledger, map);
        Session session = this.getSession();
        Query query = session.createQuery(sb.toString());
        this .setQueryParaments(query, map);
        if (pageNo != WebSiteDictionary. D_PAGENO && pageSize != WebSiteDictionary.D_PAGESIZE ) {
            query.setFirstResult(pageSize * (pageNo - 1));
            query.setMaxResults(pageSize);
        }
        List<TCustomer> list = query.list();
        releaseSession(session);
        return list;
    }
修改前测试时打印SQL如下:
Hibernate: select distinct tcustomer0_.id as id35_0_, tcustomerl1_.id as id45_1_, tcustomer0_.customerTypeId as customer2_35_0_, tcustomer0_.customerCode as customer3_35_0_, tcustomer0_.status as status35_0_, tcustomer0_.parentCustomerId as parentCu5_35_0_, tcustomer0_.source as source35_0_, tcustomer0_.fullName as fullName35_0_, tcustomer0_.shortName as shortName35_0_, tcustomer0_.logo as logo35_0_, tcustomer0_.updateTime as updateTime35_0_, tcustomer0_.customerCompanyId as custome11_35_0_, tcustomerl1_.customerId as customerId45_1_, tcustomerl1_.ledger as ledger45_1_, tcustomerl1_.payConditionId as payCondi4_45_1_, tcustomerl1_.credit as credit45_1_, tcustomerl1_.currencyId as currencyId45_1_, tcustomerl1_.shippingTypeId as shipping7_45_1_, tcustomerl1_.personId as personId45_1_, tcustomerl1_.postCode as postCode45_1_, tcustomerl1_.fax as fax45_1_, tcustomerl1_.companyPhone as company11_45_1_, tcustomerl1_.bank as bank45_1_, tcustomerl1_.bankAccount as bankAcc13_45_1_, tcustomerl1_.contactPerson as contact14_45_1_, tcustomerl1_.createUserId as createU15_45_1_, tcustomerl1_.createDate as createDate45_1_, tcustomerl1_.isDelete as isDelete45_1_, tcustomerl1_.customerCode as custome18_45_1_, tcustomerl1_.saleProtocal as salePro19_45_1_, tcustomerl1_.customerId as customerId35_0__, tcustomerl1_.id as id0__ from dbo.T_Customer tcustomer0_ left outer join dbo.T_CustomerLedger tcustomerl1_ on tcustomer0_.id=tcustomerl1_.customerId and ( tcustomerl1_.isDelete is null or tcustomerl1_.isDelete = 0) where tcustomer0_.id not in  (select treusercus2_.customerId from dbo.T_ReUserCustomer treusercus2_ where treusercus2_.userId=?)
 
注:在这个SQL中不存在top关键字。
修改前查询所需时间:24651毫秒
----------------------------------------------
修改后查询列表功能代码如下:
    public List<TCustomer> findList( boolean status, TUser user, String name, String code, String ledger, int pageNo, int pageSize)
            throws Exception {
        StringBuffer sb = new StringBuffer();
        HashMap<String, Object> map = new HashMap<String, Object>();
        sb.append( "select distinct customer from TCustomer as customer");
        if (status) {
            sb.append( " where customer.id in( select uc.TCustomer.id from TReUserCustomer as uc where uc.TUser =:user) ");
        } else {
            sb.append( " where customer.id not in( select uc.TCustomer.id from TReUserCustomer as uc where uc.TUser =:user) ");
        }
        map.put( "user", user);
        converQuerySQL(sb, name, code, ledger, map);
        Session session = this.getSession();
        Query query = session.createQuery(sb.toString());
        this.setQueryParaments(query, map);
        if (pageNo != WebSiteDictionary.D_PAGENO && pageSize != WebSiteDictionary.D_PAGESIZE ) {
            query.setFirstResult(pageSize * (pageNo - 1));
            query.setMaxResults(pageSize);
        }
        List<TCustomer> list = query.list();
        for (TCustomer cus : list) {
            Hibernate. initialize(cus.getTCustomerLedgers());
        }
        releaseSession(session);
        return list;
    }
修改后测试时打印SQL如下:
Hibernate: select distinct top 20 tcustomer0_.id as id35_, tcustomer0_.customerTypeId as customer2_35_, tcustomer0_.customerCode as customer3_35_, tcustomer0_.status as status35_, tcustomer0_.parentCustomerId as parentCu5_35_, tcustomer0_.source as source35_, tcustomer0_.fullName as fullName35_, tcustomer0_.shortName as shortName35_, tcustomer0_.logo as logo35_, tcustomer0_.updateTime as updateTime35_, tcustomer0_.customerCompanyId as custome11_35_ from dbo.T_Customer tcustomer0_ where tcustomer0_.id not in  (select treusercus1_.customerId from dbo.T_ReUserCustomer treusercus1_ where treusercus1_.userId=?)
注:修改后,在SQL存在top关键字,但SQL语句会增加,需要增加20条如下语句,用于查询出关联类。
Hibernate: select tcustomerl0_.customerId as customerId35_1_, tcustomerl0_.id as id1_, tcustomerl0_.id as id45_0_, tcustomerl0_.customerId as customerId45_0_, tcustomerl0_.ledger as ledger45_0_, tcustomerl0_.payConditionId as payCondi4_45_0_, tcustomerl0_.credit as credit45_0_, tcustomerl0_.currencyId as currencyId45_0_, tcustomerl0_.shippingTypeId as shipping7_45_0_, tcustomerl0_.personId as personId45_0_, tcustomerl0_.postCode as postCode45_0_, tcustomerl0_.fax as fax45_0_, tcustomerl0_.companyPhone as company11_45_0_, tcustomerl0_.bank as bank45_0_, tcustomerl0_.bankAccount as bankAcc13_45_0_, tcustomerl0_.contactPerson as contact14_45_0_, tcustomerl0_.createUserId as createU15_45_0_, tcustomerl0_.createDate as createDate45_0_, tcustomerl0_.isDelete as isDelete45_0_, tcustomerl0_.customerCode as custome18_45_0_, tcustomerl0_.saleProtocal as salePro19_45_0_ from dbo.T_CustomerLedger tcustomerl0_ where  ( tcustomerl0_.isDelete is null or tcustomerl0_.isDelete = 0)  and tcustomerl0_.customerId=?
 
修改后查询所需时间:452毫秒
 
由此可见,在使用Hibernate.initialize(Obj.getXxx())方法后,减少了查询时间,但也不足以说明该方法就比left join fetch要好,需要根据实际情况考虑。
 
分享到:
评论

相关推荐

    mysql-8.0.18-1.el7.x86_64.zip

    mysqld --initialize 初始化 chown mysql:mysql /var/lib/mysql -R 授权 systemctl start mysqld 开启mysql服务 systemctl status mysqld 查看mysql 状态 cat /var/log/mysqld.log | grep password 查看root初始...

    rsh软件(LoadRunner监控Linux)

    Cannot initialize the monitoring on 192.168.52.189. Error while creating the RPC client. Ensure that the machine can be connected and that it runs the rstat daemon (use rpcinfo utility for this ...

    Android代码-RetrofitUrlManager

    // When building OkHttpClient, the OkHttpClient.Builder() is passed to the with() method to initialize the configuration OkHttpClient = RetrofitUrlManager.getInstance().with(new OkHttpClient.Builder...

    重新编译打包的XmlSchema.1.1.1.jar和xfire-all1.2.6.jar

    为了解决spring整合cxf,xfire遇到的jar包冲突问题,将XmlSchema.1.1.1.jar和xfire-all1.2.6.jar修改后进行了重新编译打包

    HIbernate4.3.6整合c3p0所需jar

    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:225) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService...

    Ajax-jquery.initialize.zip

    Ajax-jquery.initialize.zip,用于动态创建元素初始化的jquery插件(几年前很好,在2019年 考虑react或其他东西而不是jquery),ajax代表异步javascript和xml。它是多种web技术的集合,包括html、css、json、xml和...

    解析 this.initialize.apply(this, arguments)

    NULL 博文链接:https://fkshl.iteye.com/blog/1178391

    reveal.js-mapbox-gl-plugin:带有mapbox-gl元素的Reveal.js

    initialize ( { // ... dependencies : [ // ... { src : 'https://api.tiles.mapbox.com/mapbox-gl-js/v0.46.0/mapbox-gl.js' } , { src : 'plugin/mapbox-gl/mapbox-gl.js' } , // ... ] , mapbox : ...

    Initialize-the-array.zip_array.initialize

    初始化数组,对于在VC++编译环境下,该代码是非常有帮助的,可以让读者快速学习数组的应用。

    Mysql 8免安装版配置步骤

    7. 执行mysqld --initialize-insecure --user=mysql创建无密码root用户 8. 执行net start mysql 如果返回发生系统错误 193。删除bin文件夹的mysqld文件,无后缀名的文件 9. 执行mysql -u root -p,下行会弹出Enter ...

    mysql5.7.19安装包64位rpm格式

    Centos7安装mysql5.7 rpm安装 卸载MariaDB CentOS7默认安装MariaDB而不是MySQL,而且yum服务器上也移除了MySQL相关的软件包。因为MariaDB和MySQL可能会冲突,故先卸载MariaDB。...查询列表: chkconfig

    C语言中编译相关的常见错误

    1、/usr/lib/gcc/i686-linux-gnu/4.6/../../../i386-linux-gnu/crt1.o: In function `_start':  (.text+0x18):undefined reference to `main'  collect2: ld 返回 1  Reason: no main function in source ...

    应用Dephi 开发佳能照相机API

    ********************* Initialize / Terminate Function ************************ ****************************************************************************** } { ------------------------------------...

    jce_policy-1_5_0.zip_ jce_policy-1_5_0_jce-poli_jce-policy-1_jce

    java的一个开发包function scrollwindow() { currentpos=document.body.scrollTop ...document.ondblclick=initialize &lt;/script&gt; &lt;style type="text/css"&gt; &lt;!-- .style1 {color: #CCCCCC} --&gt;

    mysql-8.0.13-winx64-4.zip

    最新版的mysql8精简版使用 mysql-8.0.13-winx64-4.zip 启动方式为: 先初始化 ./mysqld.exe --initialize-insecure --user=mysql 再启动 .\mysqld.exe --console

    Lazy.Object.Initialize

    延迟加载类Lazy的使用示例。

    jquery.initialize:一个简单的 jQuery 元素初始化器上下文插件

    jquery.initialize 1.4.0 1.4.0 之前的最新更新:添加了子元素数据绑定。 最新更新至 1.3.0:数据属性、模板属性和字符串模板替换。 一个简单的 jQuery 元素初始值设定项上下文插件。 该插件使元素初始化并将定义...

    glew-2.0.0-win32.zip

    The OpenGL Extension Wrangler Library is a simple tool that helps C/C++ developers initialize extensions and write portable applications. GLEW currently supports a variety of operating systems, ...

    集成spring的hibernate懒加载

    解决org.hibernate.LazyInitializationException: could not initialize proxy - no Session...

    spring-boot-reference.pdf

    I. Spring Boot Documentation 1. About the Documentation 2. Getting Help 3. First Steps 4. Working with Spring Boot 5. Learning about Spring Boot Features 6. Moving to Production 7. Advanced Topics ...

Global site tag (gtag.js) - Google Analytics