Java – how JPA adds a unique constraint on the column of the @ onetomany relationship, for example, on the user name
•
Java
I have a class website representing websites and class users The site can have multiple users
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 the same user name on all websites, but only one website is allowed
Site/User/username 1 /1 /username1 1 /2 /username2 2 /3 /username1
How can I do this?
Solution
Let users have Site References:
@ManyToOne(optional=false) private Site site;
Now add the constraint to the user:
@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "username","site" })) } @Entity public class User{ // etc }
You must also change the site mapping:
@OneToMany(mappedBy="site") private List<User> users;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码