JPA中的NamedQuery注释有什么好处? [英] What is the benefit of the NamedQuery annotation in JPA?

查看:72
本文介绍了JPA中的NamedQuery注释有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我为JPA实体写了NamedQuery,对此感到非常高兴.

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

在这里.

@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

}

随用法

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

一个人也可以省略NamedQuery批注而只是

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

    }

随用法

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

问题是.第一个示例的好处是什么?

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

推荐答案

主要优点是,通常在应用程序启动时对命名查询进行验证和解析.这意味着如果有任何问题,它将立即报告,并且该应用程序将无法启动.

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.

这篇关于JPA中的NamedQuery注释有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆