Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7183301
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T17:57:05+00:00 2026-05-28T17:57:05+00:00

We’re using Criteria frequently in our project for dynamic query generation. I really love

  • 0

We’re using Criteria frequently in our project for dynamic query generation. I really love the way queries are expressed. The problem is that we’ve found that this particular query cannot be made to use indexes based on clientId, and so we need to change it. Here is the working non-indexed query:

public List<EventInstance> getEventInstances(Date from, Date to, Integer clientId) {
    Session session = this.getSession();

    Criteria criteria = session.createCriteria(EventInstance.class);

    if(clientId != null){

        criteria.add(Restrictions.disjunction()
            .add(Restrictions.eq("clientId", clientId))
            .add(Restrictions.eq("team1ClientId", clientId))
            .add(Restrictions.eq("team2ClientId", clientId))
            );
    }

    if(from != null){
        criteria.add(Restrictions.ge("startTime", from));
    }

    if(to != null){
        criteria.add(Restrictions.le("startTime", to));
    }

    @SuppressWarnings("unchecked")
    List<EventInstance> events = criteria.list();

    this.releaseSession(session);
    return events;
}

This query can only use the startTime index, and is unable to use indexes with any of the clientId’s. I found that the following form of the query uses our indexes effectively, and I want to create this query with criteria:

select * from ( select * from eventInstance where (clientId = 8 or team1ClientId = 8 or team2ClientId = 8) ) evtalias where evtalias.startTime < now()

I have been able to do a sub-select in the WHERE clause with this code:

public List<EventInstance> getEventInstances(Date from, Date to, Integer clientId){
    Session session = this.getSession();

    DetachedCriteria subSelectClient = DetachedCriteria.forClass(EventInstance.class);
    if(clientId != null){
        subSelectClient.add(Restrictions.disjunction()
            .add(Restrictions.eq("clientId", clientId))
            .add(Restrictions.eq("team1ClientId", clientId))
            .add(Restrictions.eq("team2ClientId", clientId))
            )
            .setProjection(Property.forName("id"));
    }


    Criteria criteria = session.createCriteria(EventInstance.class);

    if(clientId != null){
        criteria.add(Property.forName("id").in(subSelectClient));
    }

    if(from != null){
        criteria.add(Restrictions.ge("startTime", from));
    }

    if(to != null){
        criteria.add(Restrictions.le("startTime", to));
    }

    @SuppressWarnings("unchecked")
    List<EventInstance> events = criteria.list();

    this.releaseSession(session);
    return events;
}

This generates a query like this:

select * from eventInstance this_ where this_.id in (select this_.id as y0_ from eventInstance this_ where (this_.clientId=8 or this_.team1ClientId=8 or this_.team2ClientId=8)) and this_.startTime<=now();

Which is even worse at using the indexes than my original query, and does not subselect in FROM.

So my question is, can I do this in criteria, or am I stuck with HQL or even native SQL. Alternatively if you know how to create an index that will work that would solve my problem, but my understanding from the mysql documentation is that this is impossible.

Here is the output from explain for the target query I want to create:

mysql> explain select * from ( select * from eventInstance where (clientId = 8 or     team1ClientId = 8 or team2ClientId = 8) ) evtalias where evtalias.startTime < now();
+----+-------------+---------------+-------------+-------------------------------+-----    ------------------+---------+------+------+------------------------------------------------    --------------+
| id | select_type | table         | type        | possible_keys                 | key                    | key_len | ref  | rows | Extra                                                        |
+----+-------------+---------------+-------------+-------------------------------+-----------------------+---------+------+------+--------------------------------------------------------------+
|  1 | PRIMARY     | <derived2>    | ALL         | NULL                          | NULL                   | NULL    | NULL |  288 | Using where                                                  |
|  2 | DERIVED     | eventInstance | index_merge | eijoin2,ei_client,team2,team1 | ei_client,team1,team2 | 5,5,5   | NULL |  300 | Using union(ei_client,team1,team2); Using where; Using index |
+----+-------------+---------------+-------------+-------------------------------+-----------------------+---------+------+------+--------------------------------------------------------------+
2 rows in set (0.00 sec)

And this is the explain from hibernate’s criteria subquery:

+----+--------------------+-------+-----------------+---------------------------------------+---------+---------+------+-------+-------------+
| id | select_type        | table | type            | possible_keys                         | key     | key_len | ref  | rows  | Extra       |
+----+--------------------+-------+-----------------+---------------------------------------+---------+---------+------+-------+-------------+
|  1 | PRIMARY            | this_ | ALL             | ei3                                   | NULL    | NULL    | NULL | 49434 | Using where |
|  2 | DEPENDENT SUBQUERY | this_ | unique_subquery | PRIMARY,eijoin2,ei_client,team2,team1 | PRIMARY | 4       | func |     1 | Using where |
+----+--------------------+-------+-----------------+---------------------------------------+---------+---------+------+-------+-------------+
2 rows in set (0.00 sec)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T17:57:06+00:00Added an answer on May 28, 2026 at 5:57 pm

    As far as I know, neither Criteria nor HQL can produce queries with subqueries in from clause, so that you have to use native SQL.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We're building an app, our first using Rails 3, and we're having to build
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am reading a book about Javascript and jQuery and using one of the
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I am currently running into a problem where an element is coming back from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.