0

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

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

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

谢谢。

首先,我有用户类:

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

  ...

}
4

0 回答 0