【问题标题】:Problems with @Column() annotation when I use the unique = true constraint当我使用 unique = true 约束时,@Column() 注释的问题
【发布时间】:2021-07-31 12:12:00
【问题描述】:

我正在 Spring Boot 中进行基本用户注册,我使用了 @Column(unique = true) 注释,但它不起作用。我可以用同一个邮箱注册多个用户。

这是我的代码:

package io.agile.ppmtool.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import java.util.Collection;
import java.util.Date;

@Entity @Getter @Setter @NoArgsConstructor
public class User implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Email(message = "Username needs to be an email")
    @NotBlank(message = "username is required")
    @Column(unique = true)
    private String username;
    @NotBlank(message = "Please enter your full name")
    private String fullName;
    @NotBlank(message = "Password field is required")
    private String password;
    @Transient
    private String confirmPassword;
    private Date created_At;
    private Date updated_At;
}

我希望有人能帮助我为什么这个注释对我不起作用。

【问题讨论】:

  • 你有 liquibase 如果有你也必须更改 liquibase 文件
  • 不,我没有

标签: java spring spring-boot annotations


【解决方案1】:

@Column 中的unique 仅在您让 JPA 提供程序为您创建数据库时使用 - 它将在指定列上创建唯一约束。

但如果您已经拥有数据库,或者您在创建后更改了它,那么unique 没有任何效果。

所以你需要数据库中的唯一约束,只有@Column 是不能保证的。

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 2013-02-28
    • 2020-09-29
    • 2021-03-10
    • 2011-03-30
    • 2011-08-31
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多