JPA 查询仅选择特定列而不使用标准查询? [英] JPA Query selecting only specific columns without using Criteria Query?

查看:33
本文介绍了JPA 查询仅选择特定列而不使用标准查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 JPA 查询而不使用条件查询仅从对象中选择属性 A 和 B?

Is it possible to select, say, only properties A and B from an object using a JPA query without using criteria queries?

要选择所有属性,我只需执行以下操作:

To select all properties I'd just do something like:

SELECT i FROM ObjectName i WHERE i.id = 10

但我在旧系统上有一个具有许多属性的对象,我想只选择几个,尽管我知道选择多个属性通常很快.

But I have an object with many properties on a legacy system, and want to select just a few even though I'm aware selecting several properties is usually quick.

这是否可以不使用条件查询?

Is this possible without using criteria queries?

推荐答案

是的,就像在普通 sql 中一样,您可以指定要选择的属性类型:

Yes, like in plain sql you could specify what kind of properties you want to select:

SELECT i.firstProperty, i.secondProperty FROM ObjectName i WHERE i.id=10

执行此查询将返回一个 Object[] 列表,其中每个数组包含一个对象的选定属性.

Executing this query will return a list of Object[], where each array contains the selected properties of one object.

另一种方法是将选定的属性包装在自定义对象中并在 TypedQuery 中执行:

Another way is to wrap the selected properties in a custom object and execute it in a TypedQuery:

String query = "SELECT NEW CustomObject(i.firstProperty, i.secondProperty) FROM ObjectName i WHERE i.id=10";
TypedQuery<CustomObject> typedQuery = em.createQuery(query , CustomObject.class);
List<CustomObject> results = typedQuery.getResultList();

示例可以在这篇文章中找到.

Examples can be found in this article.

2018 年 3 月 29 日更新:

UPDATE 29.03.2018:

@Krish:

@PatrickLeitermann 对我来说它给出了Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate class ***" 异常.如何解决这个问题?

@PatrickLeitermann for me its giving "Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate class ***" exception . how to solve this ?

我猜您是在 Spring 应用程序的上下文中使用 JPA,不是吗?其他一些人完全同样的问题他们的解决方案是在 SELECT NEW 关键字之后添加完全限定名称(例如 com.example.CustomObject).

I guess you’re using JPA in the context of a Spring application, don't you? Some other people had exactly the same problem and their solution was adding the fully qualified name (e. g. com.example.CustomObject) after the SELECT NEW keywords.

也许 Spring 数据框架的内部实现只识别带有 @Entity 注释的类或通过其简单名称在特定 orm 文件中注册的类,这导致使用此解决方法.

Maybe the internal implementation of the Spring data framework only recognizes classes annotated with @Entity or registered in a specific orm file by their simple name, which causes using this workaround.

这篇关于JPA 查询仅选择特定列而不使用标准查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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