Issue
Job entity
@Column(name = "name")
private String name;
@ManyToMany
@JoinTable(name = "user_job",
joinColumns = @JoinColumn(name = "job_id"),
inverseJoinColumns = @JoinColumn(name = "user_id")
)
private List<User> user;
User entity
@Column(name = "email")
private String email;
@ManyToMany
@JoinTable(name = "user_job",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id")
)
private Set<Role> roles;
Role entity
@Column(name = "name")
private String name;
@ManyToMany(mappedBy = "roles")
private Set<User> users;
Here we have a table user_job with 3 ids and I want to insert data in service layer. How I can do it and what repository I should implement or use existent like user/role/job?
class UserJobService{
public void setUserJob(User user, Job job, Role role){
}
}
Solution
The problem with @ManyToMany
association is you can't delete a record directly from user_job
table, using Hibernate. To delete the record, you need to load a user with all his jobs. So better to add UserJobEntity
@Entity
@Table(name = "USER_JOBS")
class UserJobEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "USER_ID")
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "JOB_ID")
private Job job;
}
public UserJobEntity createUserJob(UserEntity user, JobEntity job) {
UserJobEntity userJob = new UserJobEntity();
userJob.setUser(user);
userJob.setJob(job);
return userJobRepository.save(userJob);
}
Probably you will want to add (user, job) unique constraint to user_jobs
table.
Some advices
- Use plurals for table names.
user_jobs
in place ofuser_job
Role
is tabular data. So it shouldn't have a usersList
.- Don't use
Set
for associated collections. Definitely you will encounter "multiple bugs fetch exception" and this exception will help you to change queries. WithSet
you can have large cross products and even don't notice them.
Answered By - v.ladynev