在多个列上创建复合唯一约束 [英] Creating a composite Unique constraints on multiple columns

查看:226
本文介绍了在多个列上创建复合唯一约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的模特:

  class User {...} 
class Book {
用户作者;
int number;
}

每个书籍编号从每个作者的1开始并向上递增。因此,我们将获得John Grisham的书籍1,2,3,George Martin的书籍1 ...等等...



我能有一个独特的约束吗?放在预订上,这可以保证我们没有同一作者拥有相同编号的两本书?类似于 @Column(unique = true),但约束仅适用于作者X编号的复合?使用 @UniqueConstraint

  @Table(
uniqueConstraints =
@UniqueConstraint(columnNames = {author_id,number})

@Entity
class Book extends型号{
@ManyToOne
@JoinColumn(name =author_id)
用户作者;
int number;
}


This is my model:

class User {...}
class Book {
  User author;
  int number;
}

Every book number starts at 1 per author and increments upwards. So we'll have Books 1,2,3 by John Grisham, Book 1..5 by George Martin, etc...

Is there a unique constraint I can place on Book, that would guarantee we don't have two books with the same number by the same author? Similar to @Column(unique = true), but the constraint only applies on the composite of Author X number?

解决方案

Use @UniqueConstraint:

@Table(
    uniqueConstraints=
        @UniqueConstraint(columnNames={"author_id", "number"})
)
@Entity
class Book extends Model {
   @ManyToOne
   @JoinColumn(name = "author_id")
   User author;
   int number; 
} 

这篇关于在多个列上创建复合唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆