Search code examples
javahibernateentity

Why @Column(unique = true) does not work?


I have following code:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "FIRST_NAME")
    private String firstName;

    @Column(name = "LAST_NAME")
    private String lastName;

    @NotNull
    @Column(name = "LOGIN", unique = true)
    private String login;

    @Column(name = "PASSWORD")
    private String password;

    @Column(name = "ROLE")
    private UserRole role;

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

    @Convert(converter = UserStrategyConverter.class)
    @Column(name = "STRATEGY")
    private UserStrategy userStrategy;

    @Column(name = "SUBSCRIPTION")
    private Boolean subscription;

    @Column(name = "MONEY")
    private BigDecimal money;

My problem: When I put this object from postman in json:

{
    "firstName": "Daniel",
    "lastName": "xxx",

    "password": "daniel",
    "role": "ROLE_USER",
    "email": "[email protected]",
    "subscription": false,
    "money": "1200"
}

It create object in entity. Problem is because I can multiply this object again and again instead of unique = true in columns (email and login). Can anyone explain me why?


Solution

  • Hibernate will take into account the constraint unique = true only at the time of schema generation.

    During schema generation the following constraint will be added:

    alter table User
    add constraint UK_u31e1frmjp9mxf8k8tmp990i unique (email)
    

    If you do not use the schema generation there is no sense of using unique = true.