How to create join table with JPA annotations?

You definitely shouldn’t create User_Group entity as it’s more the underlying database representation than the object oriented one.

You can achieve the join table by defining something like:

@Entity
@Table(name="USERS", schema="ADMIN")
public class User implements Serializable {
//...

@ManyToOne
@JoinTable(name="USER_GROUP")
Group group;

@Entity
@Table(name="GROUPS", schema="ADMIN")
public class Group implements Serializable {
//...

@OneToMany(mappedBy="group")
Set<User> users;

Edit: If you want to explicitly set the names of the columns you could use @JoinColumn elements as shown below:

@ManyToOne
@JoinTable(name="USER_GROUP",
    joinColumns = @JoinColumn(name = "userid", 
                              referencedColumnName = "userid"), 
    inverseJoinColumns = @JoinColumn(name = "groupid", 
                              referencedColumnName = "groupid"))
Group group;

Leave a Comment