How to create join table with JPA annotations? How to create join table with JPA annotations? database database

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;


I would implement it this way:

@Entity@Table(name="GROUPS", schema="ADMIN")public class Group implements Serializable {  @OneToMany  @JoinTable(name = "USER_GROUP",            joinColumns = @JoinColumn(name = "groupid"),            inverseJoinColumns = @JoinColumn(name = "userid"))  private List<User> users;}

Solution suggested by @PedroKowalski should work too, but then you'll have to keep a reference to Group entity in your User entity which is not always possible.


To have the same annotations like in your diagram you can do this in your User class:

@ManyToMany(fetch = FetchType.LAZY)@JoinTable(name = "USER_GROUP",            joinColumns = { @JoinColumn(name = "userid") },            inverseJoinColumns = { @JoinColumn(name = "groupid") })private List<Group> grups;

in your group class

@ManyToMany(fetch = FetchType.LAZY)@JoinTable(name = "USER_GROUP",            joinColumns = { @JoinColumn(name = "groupid") },            inverseJoinColumns = { @JoinColumn(name = "userid") })private List<User> users;