Le 'nton
Le 'nton

Reputation: 366

Hibernate unique in two columns

Given a table of users with a username and email. Users can use username and email to log in. A user can choose an email as his username.

When a user changes his username or email, the new value must be unique in the set of all usernames and emails combined.

Is it possible to model this with hibernate notations, or would you need to do this at a higher level, like Java validation routines?

Small example:

| username | email      |
|----------+------------|
| user1    | [email protected] |
| user2    | [email protected] |

user2 changing his username to [email protected] should be an illegal action, since user1 already has this value as his email.

Upvotes: 4

Views: 3219

Answers (2)

Le 'nton
Le 'nton

Reputation: 366

As @coladict said:

then what you want is not supported by JPA or Hibernate. You can add a check constraint if your database version is 8.0.16 or above, but otherwise you'll have to do it manually before calling persist(user)

This is not in the realm of possibilities for hibernate. Our sollution is to do the check when validating the object. Of course this comes at the cost of computation and we have to make sure we have corresponding indices in the DB, to reduce the query time as best as possible.

Upvotes: 0

Varun Jain
Varun Jain

Reputation: 1421

Here is the sample code for your reference.

@Entity()
@Table(name = "users",uniqueConstraints= @UniqueConstraint(columnNames = {"email", "username"}) )
public class Employee {

    @Column(name = "username")
    private String username;

    @Column(name = "email")
    private String email;

    //All other user entity fields and getters/setters etc......
}

Here is the link for your reference.

Upvotes: 2

Related Questions