What is the benefit of the NamedQuery annotation in JPA?

偶尔善良 提交于 2021-02-05 09:16:06

问题


Just now I wrote a NamedQuery for a JPA entity and was very happy about that.

Here it is.

@NamedQuery(name=Panties.RED_PANTIES_QRY, query="SELECT p FROM Panties p WHERE p.color = red")
public class Panties implements Serializable {

    public static final String RED_PANTIES_QRY = "panties.red_panties";

   //getters and setters

}

With the usage

  entityManager.createNamedQuery(Panties.RED_PANTIES_QRY).getResultList();

One could also omit the NamedQuery annotation and just do

public class Panties implements Serializable {

        public static final String RED_PANTIES_QRY = "SELECT p FROM Panties p WHERE p.color = red";

       //getters and setters

    }

With the usage

entityManager.createQuery(Panties.RED_PANTIES_QRY).getResultList();

So the question is. What is the benefit of the first example?


回答1:


The main benefit is that named queries are validated and parsed typically on application startup. That means if anything is wrong with it, it will be reported immediately, and the application won't start.

Beside validation, the query is prepared once and ready for usage anywhere in the app. So, any subsequent usage of named query will not cause any additional processing, which is good for performance.



来源:https://stackoverflow.com/questions/29609511/what-is-the-benefit-of-the-namedquery-annotation-in-jpa

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!