BerndGit BerndGit - 2 months ago 14
Java Question

non-repeatable @NamedQuery

I want to define serveral named queries like:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;


@Entity
@Table(name = "TableA")
@NamedQuery(query = "SELECT i FROM TableA i WHERE i.Id = :Id", name = "findAById")
@NamedQuery(query = "SELECT i FROM TableA i WHERE i.name = :name", name = "findAByName")
public class TableA
{
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;

@Column(name="Name")
String name = "";

\\... more code


}


But doing so, I get the following error message in eclipse:


Duplicate annotation of non-repeatable type @NamedQuery. Only
annotation types marked @Repeatable can be used multiple times at one
target.


and at compilation:


java.lang.annotation.AnnotationFormatError: Duplicate annotation for
class: interface javax.persistence.NamedQuery:
@javax.persistence.NamedQuery(lockMode=NONE, hints=[], query=SELECT i
FROM TableA i WHERE i.name = :name,
name=findAByName) at
sun.reflect.annotation.AnnotationParser.parseAnnotations2(Unknown
Source)


For me this limitation of only one named Query per class makes not much sense. Is this a bug or a feature? Are there workarounds to define more Named Queries per class?

Answer

Hey you need to define as following:

@NamedQueries({
     @NamedQuery(query = "SELECT i FROM TableA i WHERE i.Id = :Id", name = "findAById"),
     @NamedQuery(query = "SELECT i FROM TableA i WHERE i.name = :name", name = "findAByName")
})