Java JPA 查询仅选择特定列而不使用标准查询?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24710626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JPA Query selecting only specific columns without using Criteria Query?
提问by Edy Bourne
Is it possible to select, say, only properties A and B from an object using a JPA query without using criteria queries?
是否可以使用 JPA 查询而不使用标准查询仅从对象中选择属性 A 和 B?
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 manyproperties 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?
这可能不使用条件查询吗?
Thank you!
谢谢!
采纳答案by Patrick Leitermann
Yes, like in plain sql you could specify what kind of properties you want to select:
是的,就像在普通 sql 中一样,您可以指定要选择的属性类型:
SELECT i.firstProperty, i.secondProperty FROM ObjectName i WHERE i.id=10
Executing this query will return a list of Object[], where each array contains the selected properties of one object.
执行此查询将返回一个 Object[] 列表,其中每个数组包含一个对象的选定属性。
Another way is to wrap the selected properties in a custom object and execute it in a TypedQuery:
另一种方法是将选定的属性包装在自定义对象中并在 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 thisarticle.
例子中可以找到这个文章。
UPDATE 29.03.2018:
2018 年 3 月 29 日更新:
@Krish:
@克里什:
@PatrickLeitermann for me its giving "Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate class ***" exception . how to solve this ?
@PatrickLeitermann 对我来说是“Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate class ***” 异常。如何解决这个问题?
I guess you're using JPA in the context of a Spring application, don't you? Some other people had exactly the same problemand their solution was adding the fully qualified name (e. g. com.example.CustomObject) after the SELECT NEWkeywords.
我猜您是在 Spring 应用程序的上下文中使用 JPA,不是吗?其他一些人有完全相同的问题,他们的解决方案是在SELECT NEW关键字后添加完全限定名称(例如 com.example.CustomObject)。
Maybe the internal implementation of the Spring data framework only recognizes classes annotated with @Entityor registered in a specific orm file by their simple name, which causes using this workaround.
也许 Spring 数据框架的内部实现只识别用@Entity注释的类或通过它们的简单名称在特定的 orm 文件中注册的类,这导致使用此解决方法。
回答by pL4Gu33
You can use something like this:
你可以使用这样的东西:
List<Object[]> list = em.createQuery("SELECT p.field1, p.field2 FROM Entity p").getResultList();
then you can iterate over it:
然后你可以迭代它:
for (Object[] obj : list){
System.out.println(obj[0]);
System.out.println(obj[1]);
}
BUTif you have only one field in query, you get a list of the type not from Object[]
但是,如果查询中只有一个字段,则会得到一个不是来自 Object[] 的类型列表
回答by SerhatCan
I suppose you could look at this link if I understood your question correctly http://www.javacodegeeks.com/2012/07/ultimate-jpa-queries-and-tips-list-part_09.html
如果我正确理解了您的问题,我想您可以查看此链接http://www.javacodegeeks.com/2012/07/ultimate-jpa-queries-and-tips-list-part_09.html
For example they created a query like:
例如,他们创建了一个查询,如:
select id, name, age, a.id as ADDRESS_ID, houseNumber, streetName ' +
20' from person p join address a on a.id = p.address_id where p.id = 1'
回答by ez121sl
Yes, it is possible. All you have to do is change your query to something like SELECT i.foo, i.bar FROM ObjectName i WHERE i.id = 10
. The result of the query will be a List
of array of Object
. The first element in each array is the value of i.foo
and the second element is the value i.bar
. See the relevant section of JPQL reference.
对的,这是可能的。您所要做的就是将您的查询更改为类似SELECT i.foo, i.bar FROM ObjectName i WHERE i.id = 10
. 查询的结果将是List
的数组Object
。每个数组中的第一个元素是值,i.foo
第二个元素是值i.bar
。请参阅JPQL 参考的相关部分。
回答by sagneta
Excellent answer! I do have a small addition. Regarding this solution:
优秀的答案!我确实有一点补充。关于这个解决方案:
TypedQuery<CustomObject> typedQuery = em.createQuery(query , String query = "SELECT NEW CustomObject(i.firstProperty, i.secondProperty) FROM ObjectName i WHERE i.id=100";
TypedQuery<CustomObject> typedQuery = em.createQuery(query , CustomObject.class);
List<CustomObject> results = typedQuery.getResultList();CustomObject.class);
To prevent a class not found error simply insert the full package name. Assuming org.company.directory is the package name of CustomObject:
为了防止类未找到错误,只需插入完整的包名。假设 org.company.directory 是 CustomObject 的包名:
String query = "SELECT NEW org.company.directory.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();
回答by Abdullah Khan
Projections
can be used to select only specific properties(columns) of an entity object.
Projections
可用于仅选择实体对象的特定属性(列)。
From the docs
从文档
Spring Data Repositories usually return the domain model when using query methods. However, sometimes, you may need to alter the view of that model for various reasons. In thissection, you will learn how to define projections to serve up simplified and reduced views of resources.
Spring Data Repositories 在使用查询方法时通常会返回域模型。但是,有时,您可能出于各种原因需要更改该模型的视图。在本节中,您将学习如何定义投影以提供简化和简化的资源视图。
Define an interface with only the getters
you want.
定义一个只有getters
你想要的接口。
interface CustomObject {
String getA(); // Actual property name is A
String getB(); // Actual property name is B
}
Now return CustomObject
from your repository like so :
现在CustomObject
从您的存储库返回,如下所示:
public interface YOU_REPOSITORY_NAME extends JpaRepository<YOUR_ENTITY, Long> {
CustomObject findByObjectName(String name);
}