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

问题描述

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

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

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

>,那么SELECT NEW就在那里,因为它有完全有效的用例,正如在第10.2.7.2节中提到的那样。 :
$ b

总之,当您不想要以类型安全的方式(而不是 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:

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语句中创建新对象 - 避免还是拥抱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:14