I need to create a join table in my database using JPA
annotations so the result will be this:
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.
I'm wondering what is the point to create a Join Table in this way, considering that we can't access directly for queries? JPA doesn't allow to make queries directly to the Join Table, so if the user want to do an operation on USER_GROUP, he has to creare a normal join query between users and groups; due to this, the join table USER_GROUP is useless.
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;
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;