本文介绍了JPA如何在@OneToMany关系的列上添加唯一约束如用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个代表网站的Site
类和一个User
类. Site
可以具有多个User
.
I have a Class Site
that represents a website and a Class User
. A Site
can have multiple 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
我该怎么做?
推荐答案
让用户获得站点引用:
@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;
这篇关于JPA如何在@OneToMany关系的列上添加唯一约束如用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!