@namedqueries
介绍
如果您是使用JPA的Java开发人员,则很可能在实体上声明了一个或多个@NamedQuery
对象。
要在类上声明@NamedQuery
,必须在类中简单地用查询名称及其JPQL进行注释,例如:
@Entity
@NamedQuery(name = "findAllProjects",query = "select p from Project p order by p.id")
public class Project
但是,如果我们想声明多个@NamedQuery
批注,注释,我们用类@NamedQueries
批注,然后包含集合@NamedQuery
注释,如下所示:
@Entity
@NamedQueries({ @NamedQuery(name = "findAllProjects",query = "select p from Project p order by p.id"),@NamedQuery(name = "findById",query = "select p from Project p where p.id=:id")
})
public class Project
枚举@NamedQuery批注
创建具有多个@NamedQuery
批注的实体后,如何检查类中存在哪些批注?
幸运的是,使用反射,枚举类中的注释并找到有关它们的详细信息非常简单,如下面的代码所示。
NamedQueries annotation = Project.class.getAnnotation(NamedQueries.class);
for (Annotation annot : annotation.value()) {System.out.println(annot.toString());for (Method method : annot.annotationType().getDeclaredMethods()) {if (method.getName().equalsIgnoreCase("name") ||method.getName().equalsIgnoreCase("query")) {try {String result = method.getName() + " : " + method.invoke(annot, null).toString();System.out.println(result);} catch (IllegalAccessException | IllegalArgumentException| InvocationTargetException e) {// Oops - something has gone wrong.break;}}}
}
运行上面的代码将产生以下输出:
@javax.persistence.NamedQuery(lockMode=NONE, hints=[], name=findAllProjects, query=select p from Project p order by p.id)
name : findAllProjects
query : select p from Project p order by p.id@javax.persistence.NamedQuery(lockMode=NONE, hints=[], name=findById, query=select p from Project p where p.id=:id)
name : findById
query : select p from Project p where p.id=:id
翻译自: https://www.javacodegeeks.com/2015/03/enumerating-namedquery-within-namedqueries.html
@namedqueries