如果实体的两个字段是(unique = true),如何处理JPA异常?

时间:2014-12-01 14:21:26

标签: java hibernate jpa

假设我有以下实体:

@Entity
@Table(name = "accounts")
public class AccountImpl implements Account {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id", nullable = false, unique = true)
  private Long id;

  @Column(name = "email", nullable = false, unique = true)
  private String email;

  @Column(name = "username", nullable = false, unique = true)
  private String username;

  // constructor + getters

}

电子邮件和用户名字段设置为唯一。现在,如果使用重复的电子邮件或另一个对象的用户名创建对象,JPA将抛出持久性异常。如何创建单独的处理程序来处理重复的电子邮件和用户名?

    Account account = new AccountImpl(email, username, password, role);
    try {
        service.createAccount(account);
    } catch(javax.persistence.PersistenceException e) {
        addFieldError("username", "Username taken");

        // Oh crap! What if the exception has been thrown by email?

        return INPUT;
    }

谢谢

2 个答案:

答案 0 :(得分:0)

一种方法是在createAccount根据username进行搜索之前,如果它返回一条记录,那么这意味着username已被采取返回适当的消息,你也可以email也是如此。

如果搜索返回none,则您知道其新帐户,然后执行createAccount

答案 1 :(得分:0)

嗯,您可以在尝试保留对象之前检查重复项,并根据结果返回正确的错误,或者保留对象...