JPQL 在 Select 语句中创建新对象 - 避免还是拥抱?
我最近了解到可以在 JPQL
语句中创建新对象,如下所示:
select new Family(mother, mate, offspr)
from DomesticCat as mother
join mother.mate as mate
left join mother.kittens as offspr
这是应该避免还是应该拥抱的事情?根据良好实践,什么时候使用此功能是合理的?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要避免它,SELECT NEW 之所以存在,是因为它有完全有效的用例,正如§10.2.7.2 中所提醒的那样。 的 SELECT 子句中的 JPQL 构造函数表达式 EJB 3.0 JPA 规范:
简而言之,当您不想以类型安全的方式(而不是
Object[]
)检索完整的实体或完整的对象图时,请使用 SELECT NEW。将查询结果映射到实体类还是非映射类将取决于您的选择。一个典型的例子是列表屏幕(您可能不需要所有详细信息)。换句话说,不要到处使用它,但不要禁止它的使用(很少有东西只是黑或白的)。
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).
当您想要检索数据传输对象时,通常会使用此类查询。也许报告是一个使用它的好地方。如果您只想检索单个域对象(例如来自 Family),那么没有理由使用它。
You often use this sort of query when you want to retrieve a Data Transfer Object. Maybe a report can be a good place to use it. If you just want to retrieve a single domain object (like from Family instead), so there is no reason to use it.
使用 new 创建的对象不一定是 DTO,即将由业务层导出的对象。它也可以是一个POJO域对象,即业务层内部使用的对象。
使用这种 POJO 作为部分对象而不是完整的 JPA 实体的原因是特定类型 JOINS 的性能。解释这一点的一个很好的资源是: https:// use-the-index-luke.com/sql/join/hash-join-partial-objects
An Object created with new does not have to be a DTO, i.e. an Object which will be exported by the Business layer. It can also be a POJO Domain Object, i.e. an Object used internally by the Business layer.
The reason to use this kind of POJOs as a partial Object instead of the full JPA Entity is performance in specific kinds of JOINS. A great resource which explains this is: https://use-the-index-luke.com/sql/join/hash-join-partial-objects