简体   繁体   中英

Hibernate JPA EntityManager.createQuery() performance

I have a query which has 2 'in' Clauses. First in clause takes around 125 values and second in clause of query takes around 21000 values. Its implemented using JPA CriteriaBuilder .

Query itself executes very fast and return results within seconds. Only problem is entityManager.createQuery(CriteriaQuery) takes around 12-13 minutes to return.

I search all over SO, all the threads are related to performance of Query.getResultList . None of them discuss about performance of entityManager.createQuery(CriteriaQuery) . If you have seen such behavior earlier, please let me know, how to resolve it.

My JDK version is 1.7. Dependency version of javaee-api is 6.0. Application is deployed on JBOSS EAP 6.4. But that's not the concern as of now, as I am testing my code using junit using EntityManager connected to actual Oracle database. If you require more information, kindly let me know.

A hybrid approach is to dynamically create a query and then save it as a named query in the entity manager factory.

At that point it becomes just like any other named query that may have been declared statically in metadata. While this may seem like a good compromise, it turns out to be useful in only a few specific cases. The main advantage it offers is if there are queries that are not known until runtime, but then reissued repeatedly. Once the dynamic query becomes a named query it will only bear the cost of processing once.

It is implementation-specific whether that cost is paid when the query is registered as a named query, or deferred until the first time it is executed.

A dynamic query can be turned into a named query by using the

EntityManagerFactory addNamedQuery()

Keep us informed by the result and good luck

I observed that, having single query with 21 IN clauses (each with 1000 expressions) and all combined with OR clauses, made query run slower. I tried another approach of executing every IN Clause as a part of separate query. So these 21 individual queries performed better overall.

Another issue I observed was that Query with CriteriaBuilder was slow when result set is huge (something like 20K rows in result set). I solved this issue by adding query hint to my typed query:

TypedQuery.setHint("org.hibernate.fetchSize", 5000);

Hope it will help others.

Code in Hibernate is not expected to be used for binding lots of params:

        for ( ImplicitParameterBinding implicitParameterBinding : parameterMetadata.implicitParameterBindings() ) {
            implicitParameterBinding.bind( jpaqlQuery );
        }

Unfortunately you need to find different approach if you want to do something similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM