There are two ways of doing it.
1. Use @IdClass
Code:
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.OneToMany;
import javax.persistence.ManyToOne;
import java.io.Serializable;
import java.util.Collection;
@Entity
public class User {
public int id;
@OneToMany(mappedBy = "user")
public Collection<UserSite> sites;
public static class UserSitePk implements Serializable {
@ManyToOne
public User user;
public String name;
}
@Entity
@IdClass(UserSitePk.class)
public static class UserSite {
@Id
public User user;
@Id
public String name;
}
}
2. Use @EmbeddedId and @Embeddable
Code:
import javax.persistence.Embeddable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import java.io.Serializable;
import java.util.Collection;
@Entity
public class User {
public int id;
@OneToMany(mappedBy = "id.user")
public Collection<UserSite> sites;
@Embeddable
public static class UserSitePk implements Serializable {
@ManyToOne
public User user;
public String name;
}
@Entity
public static class UserSite {
@EmbeddedId
public UserSitePk id;
}
}