JPQL在Select语句中创建新对象 - 避免还是拥抱? [英] JPQL Create new Object In Select Statement - avoid or embrace?

查看:135
本文介绍了JPQL在Select语句中创建新对象 - 避免还是拥抱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近了解到,可以在 JPQL 语句中创建新对象,如下所示:

 选择新家庭(母亲,队友,offspr)
从DomesticCat作为母亲
加入mother.mate作为队友
离开加入mother.kittens as offspr

这是要避免还是需要拥抱?根据良好实践,何时使用此功能是合理的?解析方案

>,那么SELECT NEW就在那里,因为它有完全有效的用例,正如在第10.2.7.2节中提到的那样。 SELECT子句中的JPQL构造函数表达式 EJB 3.0 JPA规范
$ b


可以在
SELECT列表中使用构造函数来返回一个或多个Java
实例。指定的类不是
所需的实体或
映射到数据库。
的构造函数名称必须完全符合
限定。


$ b 如果指定了实体类名称
in SELECT NEW子句中,
生成的实体实例处于
新状态。

  SELECT NEW com .acme.example.CustomerDetails(c.id,c.status,o.count)
FROM Customer c JOIN c.orders o
WHERE o.count> 100


总之,当您不想要以类型安全的方式(而不是 Object [] )检索完整的实体或完整的对象图。无论您将查询的结果映射到实体类还是非映射类都将取决于您的选择。一个典型的例子就是列表屏幕(你可能不需要所有的细节)。

换句话说,不要在任何地方使用它,但不要禁止它使用(很少的东西只有黑色或白色)。


I've learnt recently that it is possible to create new Objects in JPQL statements as follows:

select new Family(mother, mate, offspr)
from DomesticCat as mother
    join mother.mate as mate
    left join mother.kittens as offspr

Is this something to be avoided or rather to embrace? When is usage of this feature justified in the light of good practices?

解决方案

Don't avoid it, the SELECT NEW is there because there are perfectly valid use cases for it as reminded in the §10.2.7.2. JPQL Constructor Expressions in the SELECT Clause of the EJB 3.0 JPA Specification:

A constructor may be used in the SELECT list to return one or more Java instances. The specified class is not required to be an entity or to be mapped to the database. The constructor name must be fully qualified.

If an entity class name is specified in the SELECT NEW clause, the resulting entity instances are in the new state.

SELECT NEW com.acme.example.CustomerDetails(c.id, c.status, o.count)
FROM Customer c JOIN c.orders o
WHERE o.count > 100

In short, use the SELECT NEW when you don't want to retrieve a full entity or a full graph of objects in a type safe way (as opposed to an Object[]). Whether you map the result of a query in an entity class or a non mapped class will depend on your select. A typical example would be a list screen (where you might not want all the details).

In other words, don't use it everywhere but don't forbid its use (few things are only black or white).

这篇关于JPQL在Select语句中创建新对象 - 避免还是拥抱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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