Issue
So for this assignment, I'm supposed to have 2 microservices (task-service & user-service) with each having their own database. A task can have multiple users assigned it but multiple users can be assigned to multiple tasks so therefore it's a many-to-many relationship.
Both microservices are Spring Boot applications using Hibernate and I'm struggling to make this relationship happen between task and user inside the task-service because I don't think it's a good idea to copy the user model that already exists in the user-service, over to the task-service.
This assignment assumes that there is consistency in the user-ids across both databases without using foreign keys.
For context:
Desired entity relationship diagram generated from Hibernate:
Task.java [task-service]
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
public class Task extends BaseEntity {
private String name, description;
@ManyToOne
private Lane lane;
@OneToMany
private List<TaskUser> users;
}
TaskUser.java [task-service]
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Data
@EqualsAndHashCode
public class TaskUser {
@Id
private Long id;
@Column(name = "task_id")
private Long taskId;
@Column(name = "user_id")
private Long userId;
}
User.java [user-service]
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class User extends BaseEntity {
@Column(unique = true)
private String username;
}
Currently, Hibernate is generating both a task_user & task_users table inside the task-service database and I'd like to just have 1 intermediate table instead of two.
Question: How would I make this many-to-many relationship work with Hibernate whilst working with two different microservices?
Solution
Maybe a better hibernate mapping :
Task.java [task-service]
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
public class Task extends BaseEntity {
private String name, description;
@ManyToOne
private Lane lane;
@OneToMany(mappedBy="task")
private List<TaskUser> users;
}
TaskUser.java [task-service]
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Data
@EqualsAndHashCode
public class TaskUser {
@Id
private Long id;
@ManyToOne
@JoinColumn(name="task_id", nullable=false)
private Task task;
@Column(name = "user_id")
private Long userId;
}
Answered By - Mr_Thorynque