March 24, 2014

Create join table with JPA annotations

Problem:

Need to create a join table in database using JPA annotations so the DATABASE design as follows:
 and it should be like this in JPA level:

Solution:

Default entities implementation:
@Entity
@Table(name="USER")
public class User implements Serializable {
//...

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

@Entity
@Table(name="GROUP")
public class Group implements Serializable {
//...

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

Changes on User entity as follows:

@Entity
@Table(name="USER")
public class User implements Serializable {
//...
@ManyToOne @JoinTable(name="USER_GROUP",     joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "user_id"),     inverseJoinColumns = @JoinColumn(name = "group_id", referencedColumnName = "group_id")) Group group;

No comments: