限制数据库表以包含唯一数据

时间:2014-01-04 19:33:05

标签: mysql sql hibernate

我在我的项目中使用了hibernate。

我有一个Team实体:

@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对象。

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

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

例如,以下两个团队是独一无二的。可以接受,因为他们的名字不同:

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表中,只要至少有一个字段,两个团队就可以拥有相同的多个字段值。然后,他们是可区分的独特团队。

2 个答案:

答案 0 :(得分:1)

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

@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;
.
.
.
}

答案 1 :(得分:0)

您可以添加UNIQUE约束:

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;

确保每个团队必须拥有所有列唯一

相关问题