Bravo
Bravo

Reputation: 1139

How to handle JPA exceptions when two fields of an entity are (unique = true)?

Let's say I have the following entity:

@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

}

The email and username fields are set to unique. Now, if an object is being created with a duplicate email or username of another object, JPA will throw Persistence Exception. How can I create separate handlers for dealing with duplicate email and username?

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

Thank you

Upvotes: 1

Views: 720

Answers (2)

Djordje Ivanovic
Djordje Ivanovic

Reputation: 4259

Well, you can check for duplicates before trying to persist an object, and based on the result, return proper error, or persist the object...

Upvotes: 0

Sajan Chandran
Sajan Chandran

Reputation: 11487

One way would be to before do createAccount do a search based on the username if it returns a record then which means the username is already taken return appropriate message, also u could so the same thing for email.

If both the search returns none then u know its a new account, and execute createAccount.

Upvotes: 1

Related Questions