JPA查询仅选择特定列而不使用Criteria Query? [英] JPA Query selecting only specific columns without using Criteria Query?
问题描述
是否可以在不使用条件查询的情况下使用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();
例子可以在这篇文章。
更新29.03.2018:
UPDATE 29.03.2018:
@Krish:
@PatrickLeitermann对我来说它给出了引起:org.hibernate.hql.internal。 ast.QuerySyntaxException:无法找到类***异常。如何解决这个问题?
@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查询仅选择特定列而不使用Criteria Query?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!