使用GWT的GAE数据存储区,使得更友好/更小的密钥

时间:2012-08-14 13:03:49

标签: google-app-engine gwt jpa google-cloud-datastore

我目前正在使用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 /密钥,但由于String / Key密钥中内置的关系,我无法在对象上使用@OneToMany关系。

另一个选项是为每个类创建一个序列,并为该id使用Long属性。下面有一个例子,但我不知道如何在app引擎中处理生成的Long序列。

@GeneratedValue private Long friendlyClassSpecificKey;

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

1 个答案:

答案 0 :(得分:0)

我为小键提出了一个很好的解决方案。我认为干净利落的最好方法是将jpa / jdo 2用于具有无主关系的app引擎。这样,您可以仅使用其类型从(Long)id获取密钥,而不必使用父关系。

这是基本数据库对象,请注意我正在使用app引擎密钥。

@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);
    }
}