Understanding structure / syntax of nested annotations

Viewed 104

I came across following spring hibernate annotations:

@NamedQueries({ @NamedQuery(name = "@HQL_GET_ALL_ADDRESS", query = "from Address") })
@NamedNativeQueries({ @NamedNativeQuery(name = "@SQL_GET_ALL_ADDRESS", query = "select emp_id, address_line1, city, zipcode from
Address") })

I found it difficult to understand the structure /syntax of the annotation. What kind of nesting of properties does these annotations follow? Is it spring expression language? I tried to go through spring expression language documentation and I am still not able to get it.

1 Answers

There are four annotations at play in your sample code: @NamedQueries + @NamedQuery and @NamedNativeQueries + @NamedNativeQuery.

Hibernate provides them extending directly from the Java Persitence API (JPA) ones.

@NamedQueries({
   @NamedQuery(name = "@HQL_GET_ALL_ADDRESS", query = "from Address")
})
@NamedNativeQueries({
   @NamedNativeQuery(name = "@SQL_GET_ALL_ADDRESS", query = "select emp_id, address_line1, city, zipcode from Address")
})

I think your confusion comes from the fact that the names of both queries start with a @ like in @HQL_GET_ALL_ADDRESS but that's not a requirement at all. You can name your query bob if you like.

Other than that, as the name suggest, you can define multiple @NamedQuery inside of a @NamedQueries and the same goes for @NamedNativeQueries.

@NamedQueries({
   @NamedQuery(name = "get_all_address", query = "from Address"),
   @NamedQuery(name = "get_all_active_address", query = "from Address where active = true")
})

Hibernate documentation about named queries can be found here.

To expand a bit on the curly braces inside java annotations, they just mean that you can supply an array of objects instead of a single one. Think of it as if you were initializing a new array like this:

String[] items = {"one", "two", "three"};

So you supply an array to the annotation. In this particular case, it just so happens that @NamedQueries expects an array of other annotations. This is probably more clear if you check the source code for @NamedQueries:

...
public @interface NamedQueries { 

    /** (Required) An array of <code>NamedQuery</code> annotations. */
     NamedQuery [] value (); 
}

It's standard Java annotation syntax, you can see a reference with examples here.

Related