本文介绍了在多列上创建复合唯一约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的模型:
class User {...}
class Book {
User author;
int number;
}
每个作者的每本书编号从 1 开始,然后向上递增.所以我们将有约翰·格里沙姆 (John Grisham) 的第 1、2、3 卷,乔治·马丁 (George Martin) 的第 1..5 卷等……
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...
是否有我可以对 Book
施加的唯一约束,以保证我们不会有两本书具有相同作者的相同编号?与@Column(unique = true)
类似,但约束只适用于作者X编号
的组合?
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
?
推荐答案
@Table(
uniqueConstraints=
@UniqueConstraint(columnNames={"author_id", "number"})
)
@Entity
class Book extends Model {
@ManyToOne
@JoinColumn(name = "author_id")
User author;
int number;
}
这篇关于在多列上创建复合唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!