【问题标题】:restrict database table to contain unique data限制数据库表包含唯一数据
【发布时间】:2014-01-05 14:40:37
【问题描述】:

我在我的项目中使用休眠。

我有一个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 对象。

如何限制此表以包含独特的团队?我的意思是如何确保表中没有个团队对每个字段(列)都有确切的保存值?

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

例如,以下 2 个团队是独一无二的并且可以接受,因为它们的名称不同:

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

再举一个例子,我的表不应该接受以下 2 个团队(没有字段具有不同的值):

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

我的意思是在team 表中,只要有至少一个字段不同,两个团队的多个字段的值可能相同。然后,他们是与众不同的独特团队。

【问题讨论】:

  • 查看我的回答 @UniqueConstraint(columnNames = {"tid", "size","name","is_new","other"}) 这将每次处理唯一行
  • 我的意思是,在数据库表中,只要至少有一个不同的字段,两个团队的多个字段就可以具有相同的值。然后,他们是可区分的团队。你的答案符合我的要求吗?
  • Does your answer fits my requirement? 是的。
  • @leem.fn 是的,它每次都会检查唯一行,强调唯一行而不是单个唯一列
  • 让团队 name 独一无二是合适的。

标签: mysql sql hibernate


【解决方案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;
.
.
.
}

【讨论】:

    【解决方案2】:

    您可以添加一个 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;
    

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

    【讨论】:

    • 我的意思不是一列是唯一的,而是一行数据。这是为了确保没有多个团队的每个字段都相同。
    • 好的,将所有列添加到约束中。我编辑了我的答案。但我认为这足以让团队与众不同,如果名称是唯一的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多