简体   繁体   English

如何使用 JPA 创建 UNIQUE 列?

[英]How to create UNIQUE column with JPA?

My POJO is using JPA and when I apply unique value in the column is not working for me I tried to use the UniqueConstraint and also not working for me.我的 POJO 使用的是 JPA,当我在列中应用唯一值时,它对我不起作用,我尝试使用UniqueConstraint ,但对我也不起作用。

below is my code下面是我的代码

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

    public class Users {

     @Id
     @GeneratedValue(strategy = GenerationType.AUTO)
     @Column(name="user_id",unique=true,nullable = false)
     private int UserId;

     @Column(name = "username" ,unique=true,nullable = false)
     private String Username;

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

     @Column(name = "firstname",nullable = false)
     private String firstname;

     @Column(name = "lastname", nullable = false)
     private String lastname;

     @Column(name = "password", nullable = false)
     private String password;

     @Column(name = "active")
     private int active;

     @ManyToMany(cascade=CascadeType.ALL)
     @JoinTable(name="user_role", joinColumns=@JoinColumn(name="user_id"), inverseJoinColumns=@JoinColumn(name="role_id"))
     private Set<Role> roles;

below is the generated table in the database (MySQL)下面是数据库中生成的表(MySQL)

| users | CREATE TABLE users (
  user_id int(11) NOT NULL,
  username varchar(255) NOT NULL,
  active int(11) DEFAULT NULL,
  email varchar(255) NOT NULL,
  firstname varchar(255) NOT NULL,
  lastname varchar(255) NOT NULL,
  password varchar(255) NOT NULL,
  PRIMARY KEY (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 |

Hibernate log after spring start Hibernate spring 启动后登录

Hibernate: create table users (user_id integer not null, username varchar(255) not null, active integer, email varchar(255) not null, firstname varchar(255) not null, lastname varchar(255) not null, password varchar(255) not null, primary key (user_id)) engine=InnoDB Hibernate: alter table users drop index UKfnranlqhubvw04boopn028e6 Hibernate: alter table users add constraint UKfnranlqhubvw04boopn028e6 unique (username, email) Hibernate: alter table users drop index UK_r43af9ap4edm43mmtq01oddj6 Hibernate: alter table users add constraint UK_r43af9ap4edm43mmtq01oddj6 unique (username) Hibernate: alter table users drop index UK_6dotkott2kjsp8vw4d0m25fb7

Try like this:像这样尝试:

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

        public class Users {

Apparently there's nothing wrong with this code.显然这段代码没有任何问题。 unique=true in @Column is a shortcut for @UniqueConstraint(columnNames = {"user_id"} and other particular constraints. You could only use one of them except for multiple unique constraints. @Column中的unique=true@UniqueConstraint(columnNames = {"user_id"}和其他特定约束的快捷方式。除了多个唯一约束之外,您只能使用其中之一。

But if you are confused why the generated CREATE TABLE doesn't contain these unique constraints, check the log, you can find alter table commands just after CREATE TABLE .但是,如果您对为什么生成的CREATE TABLE不包含这些唯一约束感到困惑,请检查日志,您可以在CREATE TABLE之后找到alter table命令。

In this case commands could be,在这种情况下,命令可能是,

alter table users add constraint UK_some_id unique (username)
alter table users add constraint UK_some_id unique (email)

Hope this help.希望这有帮助。

in jpa the id is already unique so to make username and email unique add the statement在 jpa 中,id 已经是唯一的,因此要使用户名和电子邮件唯一添加语句

unique=true

to the corresponding @Column annotation.到相应的@Column注释。

PS : remember the unique cannot be null when insert new item you should drop the table before run the application and remove uniqueConstraints in table annotation PS:记住插入新项目时,unique不能为空,你应该在运行应用程序之前删除表并删除表注释中的uniqueConstraints

if you set unique in @Column that's mean let your JPA provider create the database for you - it will create the unique constraint on the specified column.如果您在 @Column 中设置唯一,这意味着让您的 JPA 提供程序为您创建数据库- 它将在指定的列上创建唯一约束。

But after creating a database, or you alter it once created, then unique doesn't have any effect但是在创建数据库之后,或者一旦创建更改它,那么 unique 没有任何影响

I had the same problem here, set length to your unique columns.. It worked here.我在这里遇到了同样的问题,将长度设置为您唯一的列。它在这里工作。 Do

@Column(name = "userName", length = 50, unique = true) @Column(name = "userName", length = 50, unique = true)

Set the column to have the fixed length make it work because mysql size for unique constrains limited to 1000 bytes将列设置为固定长度使其工作,因为 mysql 唯一约束的大小限制为 1000 字节

@Column(name = "username", length = 200, unique = true) @Column(name = "username", length = 200, unique = true)

Use @javax.persistence.Column(unique = true).使用@javax.persistence.Column(unique = true)。 Dont forget to restart your application.不要忘记重新启动您的应用程序。

&& you cant alter your column if there are still duplicated values in it. && 如果列中仍有重复值,则无法更改列。 drop your table, and recreate it with your generated ddl.删除您的表,并使用您生成的 ddl 重新创建它。 (if ure not usin springboot) (如果你不使用 springboot)

&& if youre using springboot, go to your application.properties & set spring.jpa.hibernate.ddl-auto to update && 如果您使用的是 springboot,请转到您的application.properties并设置spring.jpa.hibernate.ddl-auto以进行update

This updates the schema if necessary.如有必要,这会更新架构。

The column needs to be non nullable for it to be unique!该列必须不可为空才能唯一!

@Column(unique = true) will NOT work @Column(unique = true)不起作用

@Column(unique = true, nullable = false) will work @Column(unique = true, nullable = false)会起作用

If the database or schema already exists before adding the uniqueConstraints then it won't work.如果在添加uniqueConstraints之前数据库或模式已经存在,那么它将不起作用。

So drop the database or schema and run the application to create new database with these uniqueConstraints所以删除数据库或模式并运行应用程序以使用这些uniqueConstraints创建新数据库

DROP DATABASE database_name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM