Search code examples
javahibernatejpadata-access-layer

JPA why use createNamedQuery


I'm in the processes of changing my DAO layer from using Hibernate API to using a pure JPA API implementation. It looks like the recommended method is to use the createNamedQuery from the entity manager. The named queries are stored in annotations in the model/entity classes. This just not makes sense to me. Why would you define the JPA Queries in the model objects but use them in the DAOs. Wouldn't it make more sense to just use createQuery from within the DAO itself and define the queries in the DAO or even just define the named queries in the DAO itself?

For those of you that have implemented your DAO layer using the JPA API how have you defined your queries?


Solution

  • I use named queries.

    There are two reasons to do so:

    1. It puts them in a more central place rather than scattered in code with random createQuery() calls; and
    2. Build processes can validate the queries (really useful).