Search code examples
hibernategrailsgrails-ormcriteria

Where should I write my criteria queries in a Grails Project ? In the Service layer or in the Domain Models?


I am currently working on a Grails project and I need to write some queries using Hibernate Criteria.

Where should I write my Hibernate Criteria queries and why ?

Is it the service layer ? Or would it be a better idea to avoid anemic domain models and write named queries there ? Or, should I create a separate layer under the Service Layer ?


Solution

  • The short answer is "it depends".

    The longer answer is "it depends on how you are structuring your application".

    If you plan on delegating everything to a service layer then a service layer is a good place to place your queries.

    If you plan on using the same queries from multiple services or chaining them then named queries on the domain class makes more sense.

    So, "it depends" on how your application is designed. Either is an acceptable place to put queries so long as it meets your requirements and facilitates code reuse.