java JPA 如何在列上为@OneToMany 关系(如用户名)添加唯一约束
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5260895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JPA How add unique contraint on column for @OneToMany relation like on username
提问by Sebastien Dionne
I have a Class Site
that represents a website and a Class User
. A Site
can have multiple User
s.
我有一个 ClassSite
代表一个网站和一个 Class User
。ASite
可以有多个User
s。
class Site {
private int site_ID;
@OneToMany // with a join table
private List<User> users;
// ...
}
class User {
private int user_ID;
private String name;
private String lastname;
private String username;
private String password;
}
I want to allow same username to exist on all Sites, but only one by site.
我想允许所有站点上存在相同的用户名,但每个站点只能存在一个。
Site/User/username
1 /1 /username1
1 /2 /username2
2 /3 /username1
How can I do that?
我怎样才能做到这一点?
回答by Sean Patrick Floyd
Let the user have a Site reference:
让用户有一个站点引用:
@ManyToOne(optional=false)
private Site site;
Now add the constraint to user:
现在将约束添加到用户:
@Table(uniqueConstraints = {
@UniqueConstraint(columnNames = { "username", "site" }))
} @Entity
public class User{
// etc
}
You will also have to change the Site mapping:
您还必须更改站点映射:
@OneToMany(mappedBy="site")
private List<User> users;
回答by atoy
By default, the primary index on the join table is unique and based on the site and user FK So, you cannot have the same user with the same site duplicated.
默认情况下,连接表上的主索引是唯一的,并且基于站点和用户 FK 因此,您不能将相同站点的相同用户重复。
But if you want to force a constraint :
但是如果你想强制约束:
class Site {
private int site_ID;
@OneToMany // with a join table
@JoinTable(
uniqueConstraints=@UniqueConstraint(columnNames={"Site_ID","users_ID"})
)
private List<User> users;
// ...
}
回答by Bozho
Check @UniqueConstraint
. It allows defining any unique constraint
检查@UniqueConstraint
。它允许定义任何唯一约束