Search code examples
javahibernatehashmaphql

How to check the uniqueness of a record with the generated id?


I have a class:

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String name;
    private int passport;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof User)) return false;
        User user = (User) o;
        return passport == user.passport &&
                Objects.equals(name, user.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, passport);
    }
}

As you can see, the ID is generated, but the uniqueness of the record has to be checked by other fields. To do this, I use HQL:

Query query = session.createQuery("from Pilot where name:=name and passport=:passport");

How do I apply collections to check a record for uniqueness?


Solution

  • You can add unique constraint on both field passport and name. To do so you can juste add this line above your class definition

    @Table(name = "USER", uniqueConstraints = { @UniqueConstraint(columnNames = { "name", "passport" }) })
    

    So it will be like this :

    @Entity
    @Table(name = "USER", uniqueConstraints = { @UniqueConstraint(columnNames = { "name", "passport" }) })
    public class User {
    ...