JPA How to add a unique column for the @OneToMany relationship, for example, as a user

I have a good problem. I will return to the context.

I have a class: Siterepresenting a website, and a class User.

A 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 the same username to exist on all Sites, but only on the site.

Site/User/username
1   /1   /username1
1   /2   /username2
2   /3   /username1

How can i do this?

thank

+5
source share
3 answers

Let the user have a link to the site:

@ManyToOne(optional=false)
private Site site;

Now add the restriction to the user:

@Table(uniqueConstraints = {
    @UniqueConstraint(columnNames = { "username", "site" }))
} @Entity
public class User{
// etc
}

You will also have to change the display of the site:

@OneToMany(mappedBy="site")
private List<User> users;
+8
source

FK , .

:

class Site {

    private int site_ID;

    @OneToMany // with a join table
    @JoinTable(
        uniqueConstraints=@UniqueConstraint(columnNames={"Site_ID","users_ID"})
    )
    private List<User> users;
    // ...
}
+6

Check it out @UniqueConstraint. It allows you to define any unique constraint.

+1
source

All Articles