views:

2861

answers:

5

Is there a way to externalize HQL named queries to an external file. I have too many named queries and using @NamedQueries/@NamedQuery at the head of my entities classes is hurting. Is there a way to externalize to several files?

A: 

You mean like this: Externalize HQL Queries

John Ellinwood
I don't think that he means that. When you are working with annotations rather than the XML mapping file, you are using the @NamedQueries/@NamedQuery as mentioned above, which puts them inside the class.
mattsidesinger
+1  A: 

I don't think that this is possible as Annotation attribute/property values must be available at compile time. Therefore, Strings cannot be externalized to a file that needs to be read in by some sort of process.

I tried to find if there was something that package-info.java might be able to provide, but could not find anything.

An alternative strategy for organization could be storing the queries as constants in a Class.

In your entity class:

@NamedQuery(name="plane.getAll", query=NamedQueries.PLANE_GET_ALL)

Then define a class for your query constants:

public class NamedQueries {
    ...
    public static final String PLANE_GET_ALL = "select p from Plane p";
    ...
}
mattsidesinger
+1  A: 

You can put the queries into package-info.java 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 package-info.java file:

@org.hibernate.annotations.NamedQueries({
    @org.hibernate.annotations.NamedQuery(
        name = "foo.findAllUsers", 
        query="from Users") 
}) 

package com.foo.domain;

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" 
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="annotatedClasses">
      <list>
      ...
      </list>
</property>
<property name="annotatedPackages">
  <list>
      <value>com.foo.domain</value>
  </list>
</property>

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

javashlook
A: 

Can I place my named quries in a property file? So when there is a change I just need to restart the server not to recompile the project?

A: 

Kashif - did you find out how to externalize HQL named queries so that we dont have compile our code and just restart the application or server should do it.