当 super class 不是 @Entity 时,如何在 Objectify 中索引 super class 属性

How to index a super class property in Objectify when super class is not an @Entity

tl;博士: 当 属性 派生自非@Entity super class.

时,是否可以将 @Index 设置为 Objectify 实体 属性

长版:

一个 Java 项目包含抽象模型 classes,应用程序使用这些模型而不是具体对象(Objectify 实体)。对于每个这样的模型,都存在一个@Entity,它扩展了模型并为持久层(Objectify)添加了细节。

一个简单的例子:

public abstract class UserModel {
  protected String givenName;
}

@Entity
public class UserImpl extends UserModel {
  @Id
  private Long id;
}

我选择这种方法是因为我想独立于持久层使用模型 classes。因此,模型 classes 不能包含持久层特定的注释或代码。

我知道在 Morphia(一个 MongoDB ORM)中可以这样注释 @Entity class:

@Indexes(@Index(value = "superGivenName", fields = {@Field("givenName")}))

是否可以在Objectify中实现类似的效果?它不一定是带有注释的解决方案。但是,应该可以将解决方案封装在@Entity class.

注意:我会 post 一个可能的解决方案,但我正在寻找更时尚/更漂亮的东西,所以如果您有更好的想法,请不要犹豫回答。

一个可能的解决方案是隐藏应该在@Entity class 中索引的超级class 属性。然后使用@OnLoad 和@OnSave 生命周期回调在父class 和子

之间传播值

示例:

public abstract class UserModel {
  protected String givenName;
}

@Entity
public class UserImpl extends UserModel {
  @Id
  private Long id;
  @Index
  private String givenName;
  @OnLoad
  void onLoad(){
      super.givenName = this.givenName;
  }
  @OnSave
  void onSave(){
      this.givenName = super.givenName;
  }
}

我认为您不会找到令您满意的答案。 Objectify 不提供任何类似这种内置的行为。

我假设您担心 Objectify 注释会泄漏到您将广泛分发的客户端 jar(android 或某种 rpc)中。我强烈建议为您的 API 创建单独的模型 类 ,原因很简单,它将您的数据模型(将更改)与您的 API(可能会根据不同的时间表更改)分离.很难在现场升级客户端。使用单独的 类,您可以使用 IDE 重构您的数据模型,而不必担心破坏向后兼容性。

如果您使用 http://projectlombok.org,数据传输对象中涉及的样板文件几乎为零。