2

我在 Play Framework 中有以下模型。

@Entity
public class Parent extends Model {

  @Id
  public Long id;
  public String name;
  public List<Child> children = new ArrayList<Child>();

}

@Entity
public class Child extends Model {

  // Entity 2
  @Id
  public Long id
  public String name;
  @ManyToOne
  public Parent parent;

}

执行以下查询为我提供了比我需要的更多信息。

 toJson(Child.find.all());

作为一个例子,我得到了所有的孩子以及他们的父母和父母的属性以及任何其他相邻的信息。

我已经尝试设置fetch=FetchType.LAZY,但它没有任何区别。

任何人都可以帮忙吗?

4

3 回答 3

2

Jackson 的 toJson() 方法总是在序列化 Ebean 的对象时获取所有数据,因此它可以是真实的performance killer,讨论过我的提议是使用一些专用对象(未存储在 DB 中)并仅用来自“原始”对象的所需数据填充它。

检查其他答案,它描述了这种方法

于 2013-03-26T16:28:46.317 回答
1

Ebean 已内置 JSON 支持,如果您希望精确控制对象图的各个部分以包含在 JSON 中,则可以使用它:

JsonContext jsonContext = Ebean.json();
JsonWriteOptions options = JsonWriteOptions.parsePath("id,name");
String json = jsonContext.toJson(list2, options);

或者,您可以将 PathProperties 应用于查询和 json,例如:

PathProperties pathProperties = PathProperties.parse("id,name");
query.apply(pathProperties);
// fetch only id and name
List<App> list3 = query.findList();

// json output only id and name
JsonWriteOptions options2 = new JsonWriteOptions();
options2.setPathProperties(pathProperties);
String json2 = jsonContext.toJson(list3, options2);

请注意,Ebean 4.3 对其 json 支持进行了重构,以使用 Jackon 核心进行解析和生成(因此它在后台使用了 Jackson)。您正在使用 Play,因此目前停留在旧版本的 Ebean 上,因此我认为您将使用 pathProperties.apply(query) 而不是使用 query.apply()。

关于@JsonIgnore ...显然不同的用例需要不同的JSON,这就是Ebean中存在此功能的原因(当您获得需要包含父级的用例时)

PathProperties pathProperties = PathProperties.parse("id,name,parent(id,name)");
...
于 2014-12-01T01:37:27.257 回答
0

我只是选择了@JsonIgnore注释。

于 2013-05-14T23:01:19.017 回答