flybywire flybywire - 1 month ago 7x
Java Question

How do I externalize named queries in a Hibernate annotations app?

Is there a way to externalize HQL named queries to an external file. I have too many named queries and using

at the head of my entities classes is hurting.

Is there a way to externalize to several files?


You can put the queries into class, in, say, root package of your domain objects. However, you must use Hibernate's own @NamedQueries and @NamedQuery annotations, rather than those from javax.persistence.

Example file:

        name = "foo.findAllUsers", 
        query="from Users") 


Then, you have to add the package to your AnnotationConfiguration. I use Spring, so there it's a matter of setting annonatedPackages property:

<bean id="sessionFactory" 
<property name="annotatedClasses">
<property name="annotatedPackages">

You can also put type and filter definitions in the same file as well.