在appengine数据存储区中强制使用唯一字段(java)

时间:2013-09-16 08:14:03

标签: java google-app-engine google-cloud-datastore datanucleus

我有一个带有String字段emailAddress的User类,我想在其上强制执行唯一性。我无法获得可用的建议解决方案,因此我编写了以下过程,该过程似乎有效,使用了以唯一字段作为主键的单独类。

虽然它似乎有用,但它闻起来很有气味,因为我故意在没有任何错误发生时创建异常(通过尝试检索不存在的EmailAddress对象)。

任何人都可以评论此方法是否可靠,特别是在多个appengine实例中。

感谢。

首先,我有User类:

@PersistenceCapable
public class User {
  public User(String emailAddress, String otherData) {
    this.emailAddress = emailAddress;
    this.otherData = otherData;
  }

  @PrimaryKey
  @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
  private Key key;

  @Persistent
  private String emailAddress;

  @Persistent
  private String otherData;
}

然后我有一个EmailAddress类,使用电子邮件地址作为主键:

@PersistenceCapable
public class EmailAddress {
  public EmailAddress(String emailAddress) {
    this.emailAddress = emailAddress;
  }

  @PrimaryKey
  @Persistent
  private String emailAddress;
}

这些类的用法如下:

public class UserManager {

  public User createUser(String email, String otherData) {
    User user = new User(emailAddress, otherData);
    EmailAddress emailAddress = new EmailAddress(email);

    PersistenceManager pm = PMF.get().getPersistenceManager();
    Transaction tx = pm.currentTransaction();

    User persistedUser = null;  

    try {
      tx.begin();
      EmailAddress testEmailAddress = null;
      try {
        testEmailAddress = pm.getObjectById(EmailAddress.class, email);
      } catch (Exception e) {
        //
      }
      if (null != testEmailAddress) {
        throw new RuntimeException("That email address already has an account");
      }
      pm.makePersistent(emailAddress);
      persistedUser  = pm.makePersistent(user);
      txn.commit();
      return persistedUser;
    } finally {
      if (txn.isActive()) {
        txn.rollback();
      }
      pm.close();
    }
  }

  ...

}

0 个答案:

没有答案