JPA 2.0:加载实体的字段子集 [英] JPA 2.0: Load a subset of fields for an entity

查看:98
本文介绍了JPA 2.0:加载实体的字段子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体名称地址。地址实体有几个字段,其中之一是CITY。我通过调用entityManager.createQuery创建了一个查询,但我的查询仅包含select子句中的CITY字段(因为我只想加载该字段)。 CITY字段的类型是String。当我得到我的resultList时,我没有得到一个Address对象列表,而是一个Object []列表。

是否有任何方法可以创建地址列表而不是Object []的列表?我的JPA提供程序是休眠,最新版本。我想要一个解决方案,不需要使用Hibernate特有的任何东西。

解决方案

在查询中,这可以通过构造函数表达式实现。通常情况下,您可以使用自定义的DTO,但它也应该与实体一起工作。首先在你的实体中创建一个额外的构造函数,只需要所需的字段:

  public Address(){
// default构造函数
}

public地址(String city){
this.city = city;

$ / code>

您的查询可能如下所示:

 从地址a中选择新的your.package.Address(a.city)... 

请注意,生成的对象不会附加到EntityManager,所以对它的更改不会自动保持。


I have an Entity named address. The address Entity has several fields, one of which is CITY. I've created a query by calling entityManager.createQuery but my query only includes the CITY field in the select clause (because I only want to load that field). The CITY field is of type String. When I get my resultList, I do not get a list of Address objects but instead a list of Object[].

Is there any way to have a list of Address created instead of a list of Object[]? My JPA provider is hibernate, latest version. I want a solution that does not require the use of anything Hibernate specific.

解决方案

This is possible with constructor expressions in your query. Normally you would use this with a custom DTO, but it should work with the entity too. First create an additional constructor in your entity taking only the needed fields:

public Address() {
    //default constructor
}

public Address(String city) {
    this.city = city;
}

Your query could then look like this:

select new your.package.Address(a.city) from Address a where ...

Note that the resulting object is not attached to the EntityManager, so changes to it won't be automatically persisted.

这篇关于JPA 2.0:加载实体的字段子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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