2
@NamedQueries(  
   {   
 @NamedQuery(name = "GetAvailableProducts", query = new StringBuilder("").append("SELECT p   FROM Product p WHERE p.type= :type AND (p.available = 'ALL' OR").append(isTest() ? "(p.available = 'TEST' OR)"  : " ").append("p.available = :available)")),  
 }

This gives me an error it can't recognize the isTest() method. Instead of this method if I put an if statement as lik if(1==1) or something like that, it says "Attribute must be constans" in Intellij IDEA. How to solve?

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
kamaci
  • 72,915
  • 69
  • 228
  • 366
  • Is there any tricky way to do it. For example defining two namedQueries which has same names "GetAvailableProducts" and putting them in an abstract class. And implementing it in my class that has namedQueries. However the namedQuery will active which one I want. And So I will be chosed one namedQuery, and I won't change my namedQuery anymore. But I want to have that right for one time.. – kamaci Dec 20 '10 at 12:06

2 Answers2

4

The parameters of Java annotations can only be compile-time constants. This can't work.

Reference page: Annotations

Quote:

Once an annotation type is defined, you can use it to annotate declarations. An annotation is a special kind of modifier, and can be used anywhere that other modifiers (such as public, static, or final) can be used. By convention, annotations precede other modifiers. Annotations consist of an at-sign (@) followed by an annotation type and a parenthesized list of element-value pairs. The values must be compile-time constants.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
3

I don't believe you can do this from a NamedQuery.

Either create multiple named queries, or use a dynamic query instead:

 Query query = em.createQuery(...); 
dogbane
  • 266,786
  • 75
  • 396
  • 414