Mysql 将数据库表限制为包含唯一数据

Mysql 将数据库表限制为包含唯一数据,mysql,sql,hibernate,Mysql,Sql,Hibernate,我正在我的项目中使用hibernate 我有一个团队实体: @Entity @Table(name = "team") public class Team { private int tid; //primary key private int size; private String name; private boolean isNew; private String other; //Setter & Getter

我正在我的项目中使用hibernate

我有一个
团队
实体:

@Entity
@Table(name = "team")
public class Team {
     private int tid; //primary key

     private int size;
     private String name;
     private boolean isNew;
     private String other;

     //Setter & Getter
     ...
}
然后,我使用以下sql语句在MySQL数据库中创建了一个
team
表:

CREATE TABLE team (
    tid int not null auto_increment, 
    size int not null,
    name varchar(128),
    is_new bool default false,
    other varchar(128),
    PRIMARY KEY (tid)
) ENGINE innodb CHARACTER SET utf8;
此表中的每一行数据表示一个
团队
对象

如何将此表限制为包含唯一团队?我的意思是如何确保表中有没有团队对每个字段(列)都有准确的保存值


注意:我的意思不是一列(一个字段)是唯一的,而是数据行是唯一的。这是为了确保没有多个团队,每个领域都是相同的

例如,以下两个团队是唯一且可接受的,因为他们的名称不同:

Team 1: size = 3  name = "team1" isNew = true  other="nothing"
Team 2: size = 3  name = "team2" isNew = true  other="nothing"
另一个例子是,以下两个团队完全相同(没有字段具有不同的值),这是我的表不应接受的:

Team 1: size = 3  name = "team" isNew = true  other="nothing"
Team 2: size = 3  name = "team" isNew = true  other="nothing"

我的意思是,在
team
表中,两个团队可以对多个字段具有相同的值,只要至少有一个字段不同。然后,它们是可区分的独特团队。

您可以添加一个独特的约束:

CREATE TABLE team (
    tid int not null auto_increment, 
    size int not null,
    name varchar(128),
    is_new bool default false,
    other varchar(128),
    PRIMARY KEY (tid),
    CONSTRAINT uc_Name UNIQUE (size,name,is_new,other)
) ENGINE innodb CHARACTER SET utf8;

这确保了每个团队的所有列都必须是唯一的

您可以为希望组在实体中唯一的列定义唯一约束

@Entity
@Table(name = "team",
uniqueConstraints= @UniqueConstraint(columnNames = { "size","name","is_new","other"})) 
或针对每列

@Entity
@Table(name="team") 
public class Team{
.
.
.
  @Column(name = "size", unique=true)
  private String size;
.
.
.
}

我的意思不是让一列是唯一的,而是让数据行是唯一的。这是为了确保没有多个团队让每个字段都相同。好的,将所有列添加到约束中。我编辑了我的anwser。但是我认为,如果名称是uniqueSee,那么这就足够让团队与众不同了。请参见我的答案
@UniqueConstraint(columnNames={“tid”,“size”,“name”,“is_new”,“other”})
这将处理每次唯一的行,我的意思是,在数据库表中,两个团队可以对多个字段具有相同的值,只要至少有一个字段不同。然后,他们是与众不同的团队。你的答案符合我的要求吗?
你的答案符合我的要求吗?
是。@leem.fn是的每次都会检查唯一行,强调唯一行而不是单个唯一列使团队
名称
唯一才是合适的。