@namedqueries_在@NamedQueries中枚举@NamedQuery
生活随笔
收集整理的這篇文章主要介紹了
@namedqueries_在@NamedQueries中枚举@NamedQuery
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
@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
總結
以上是生活随笔為你收集整理的@namedqueries_在@NamedQueries中枚举@NamedQuery的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1.0jpa 2.0_JPA 2.1:不
- 下一篇: 七吨等于多少千克 七吨属于多少千克呢