1

我目前正在使用 GWT、GAE 并使用 JPA 作为我的 ORM。我有一个问题,GAE 生成的密钥太大而无法在带有 RequestFactory 的移动设备上使用。由于转换为 String 时 ID/KEY 的大小,小列表中的数据量非常大。

我使用字符串作为我的密钥,以便我可以处理继承。

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true")  
  protected String key;

这会创建一个非常长的键,例如“agxzbWFydGJhcnNpdGVyFAsSDUVzdGFibGlzaG1lbnQYuAIM”,并且由于在键中存储对象类型和父级而变得更大。

我需要一种方法来创建一个较小的唯一 ID,但仍然能够在 GAE 中处理继承。我尝试将 Long 作为 @Id/key,但由于 String/Key 键中内置的关系,我无法在我的对象上使用 @OneToMany 关系。

另一种选择是为每个类创建一个序列并为该 id 使用 Long 属性。下面有一个示例,但我不确定如何在应用引擎中处理生成的长序列。

@GeneratedValue private Long friendlyClassSpecificKey;

任何意见,将不胜感激。如果除了对我感兴趣的每个类类型使用序列之外还有其他选择,但如果没有,是否有为特定类创建序列(不是@ID)的示例?

4

1 回答 1

0

我为较小的键想出了一个很好的解决方案。我认为干净地做到这一点的最好方法是将 jpa/jdo 2 用于具有无主关系的应用程序引擎。这样,您可以仅使用它们的类型从 (Long) id 获取密钥,而不必使用父关系。

这是基本 datstore 对象,请注意我正在使用应用程序引擎密钥。

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class DatastoreObject {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Key key;

  public Long getId() {
    return key.getId();
  }

}

此类将使用 jpa 2 中支持的 @Unowned 属性,以便清单的密钥不包含父机构密钥。否则,您还必须传递父 id 并将其解析为基于类型的键。这是因为在拥有关系中,子键也包含父键。

@Entity
public class Establishment extends DatastoreObject {

    @Unowned
    @OneToOne(cascade = CascadeType.ALL)
    private Inventory inventory;

}

然后在我的 dao 基类中,我使用该类

public class DaoBase<T extends DatastoreObject> {

protected Class<T> clazz;

    @SuppressWarnings("unchecked")
    public DaoBase() {
        clazz = (Class<T>) ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
    }


    /**
     * Find an object by it's shortened long id
     * @param id
     * @return
     * @throws EntityNotFoundException
     */
    public T find(Long id) {
        if (id == null) {
            return null;
        }
        EntityManager em = ThreadLocalPersistenceManager.getEntityManager();

        Key key = getKey(id);

        T obj = em.find(clazz, key);
        return obj;
    }

    protected Key getKey(Long id) {
        return KeyFactory.createKey(clazz.getSimpleName(), id);
    }
}
于 2012-08-18T18:13:35.347 回答