问题
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