Skip to content

Dynamic method countByStuff() not working properly when used with where queries of domain classes #14480

Closed

Description

@OlegBritvinFAU

Dear Grails developer team,

I would like to report the following issue: When running a dynamic countByDynamicStuffBlah on a static where query of a domain class, the where code is not transformed into SQL properly. However running the same on a named query instead of a where query OR running a findByDynamicStuffBlah on the where query works correctly.

FYI: I have re-filed the issue in this tracker because it is rather a Gorm/Hibernate issue than a grails-core issue.

Steps to Reproduce

  1. Download the example application: countby.zip
  2. Unpack the zip archive somewhere
  3. Go to the new folder "countby"
  4. If you use gvm, type: gvm use grails 3.2.0.RC1
  5. Type: grails run-app
  6. Browse to http://localhost:8080/
  7. Open the following files: Bootstrap.groovy (puts together the test files), Book.groovy (the Book domain class with a where query and a named query), BookController.groovy (executes the tests and shows the results via println() )
  8. Select the Book controller in the UI (book/index)
  9. Watch the grails log and compare it to my attached log.txt

Expected Behaviour

countBy should work the same way as findBy on where queries, so if findBy returns 2 objects, so should countBy.

Actual Behaviour

countByAuthor works with the named query, however not with the where query. logSql is set to true in the project, so you can see that the named query generates "this_.is_scientific=? and this_.author_id=?", whereas "this_.is_scientific=?" is omitted in the where query.

Here is the log i got on my machine: log.txt

Have a look at the SQL statements on these lines:

  • 49: findByAuthor on where query => is_scientific condition PRESENT
  • 52: findByAuthor on named query => is_scientific condition PRESENT
  • 55: countByAuthor on where query => is_scientific condition MISSING
  • 58: countByAuthor on named query => is_scientific condition PRESENT

Environment Information

  • Operating System:
    myuser@mybox:$ cat /etc/issue
    Ubuntu 16.04.1 LTS \n \l
    myuser@mybox:
    $ uname -a
    Linux mybox 4.4.0-36-generic grails/grails-data-mapping#2009-Ubuntu SMP Thu Aug 11 18:01:55 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
  • Grails Version:
    myuser@mybox:~$ grails -v
    Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=1024m; support was removed in 8.0
    | Grails Version: 3.2.0.RC1
    | Groovy Version: 2.4.7
    | JVM Version: 1.8.0_101
  • JDK Version:
    myuser@mybox:~$ java -version
    java version "1.8.0_101"
    Java(TM) SE Runtime Environment (build 1.8.0_101-b13)
    Java HotSpot(TM) 64-Bit Server VM (build 25.101-b13, mixed mode)

Example Application

  • see zip file with example application

Futher facts

  • It all still worked in Grails 2.5.0 with hibernate4
  • The same error happens with PostgreSQL databases, not just h2

Thank you in advance for having a look at this issue!

Activity

  1. KerchumA222 commented on May 30, 2017

    @KerchumA222
    Contributor

    Just a heads up: you don't need def in front of a type. For example: def List listScientificNamedQuery = Book.namedQueryScientificOnly.list() should be List listScientificNamedQuery = Book.namedQueryScientificOnly.list()

    Also it is much easier to use integration or unit tests for this kind of thing.

  2. self-assigned this
    on Jun 8, 2018
  3. benrhine commented on Jun 8, 2018

    @benrhine
    Contributor

    After doing some research on this I have created an updated example with integration tests here to help narrow down the exact case of what is happening.

    NOTE: Please refer to the example BookIntSpec for all working cases.

    There are two failing cases. The one which you mentioned (which is returning a detached criteria and trying to add to it)

    Book.whereScientificOnly.countByAuthor(author)

    and hand writting the detached criteria for the above also fails in the same manner.

    final criteria = new DetachedCriteria(Book).build {
        eq 'isScientific', true
    }
    final count = criteria.countByAuthor(author)
    

    In both of the above queries it generates the same SQL (leaves out the isScientific)

    Hibernate: select count(*) as y0_ from book this_ where this_.author_id=? limit ?

    It appears to me that when executing the query this way the initial criteria of if isScientific is true is ignored or the statement is not executed as a whole. I have a suspicion that the the DetachedCriteria is not executing as a single statement because if you run either Book.whereScientificOnly or

    final criteria = new DetachedCriteria(Book).build {
        eq 'isScientific', true
    }
    criteria.list()
    

    you will get expected return results. Similar if you run Book.countByAuthor(author) or

    final criteria = new DetachedCriteria(Book).build {}
    final count = criteria.countByAuthor(author)
    

    You will also get the expected counts.

    In the doc on where queries it specifically discusses how detached criteria are lazy initialized and don't execute unless called which may be related to to the odd results of the above 2 cases

  4. removed their assignment
    on Jun 8, 2018
  5. jamesfredley commented on Feb 26, 2026

    @jamesfredley
    Contributor

    This was reported against Grails 3.2 / GORM 6.x. The dynamic finder and where-query interaction has been substantially reworked in Grails 7.x with improvements to how DetachedCriteria composes with dynamic method calls.

    If you are still experiencing this issue on Grails 7.x, please reopen with a minimal reproducer against the current version.

  6. jamesfredley commented on Feb 26, 2026

    @jamesfredley
    Contributor

    Correction to my earlier comment - after writing a reproduction test, this issue still exists in Grails 7.x / GORM 8.x.

    When using countByAuthor() on a where-query-filtered DetachedCriteria, the where clause filter is dropped, causing countBy to count against all records instead of the filtered subset. findAllBy works correctly on the same criteria - only countBy is affected.

    This will be addressed in an upcoming fix.

  7. jamesfredley commented on Feb 26, 2026

    @jamesfredley
    Contributor

    Fix submitted in PR #15460 - CountByFinder.buildQuery() was missing the applyDetachedCriteria() call that FindAllByFinder correctly includes. One-line fix that adds the missing call.

  8. added a commit that references this issue on Feb 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions