I am trying to figure out how to resolve the issue which I am having now.
I have three entities, Company, User and Affiliation. The Affiliation table is a link table for ManyToMany relationship between Company and User entities and has extra columns which I need to use.
On company side I have:
@JsonManagedReference
@OneToMany(mappedBy = "company", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Affiliation> affiliations = new HashSet<>();
On User side I have:
@JsonManagedReference(value="user")
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Affiliation> affiliations = new HashSet<>();
On Affiliation side I have:
@JsonBackReference
@ManyToOne(optional = false)
@JoinColumn(name = "company_id", referencedColumnName = "company_id")
private Company company;
@JsonBackReference(value = "user")
@ManyToOne(optional = false)
@JoinColumn(name = "user_id", referencedColumnName = "user_id")
private User user;
Repository class:
public interface ICompanyRepository extends JpaRepository<Company, Long>
In the service implementation class, I am issuing. The company is an updated company object.
Company updatedCompany = companyRepository.save(company);
And this is giving me
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'user_id' cannot be null.
This tells me that I have to set User somehow, but not sure how. I can only access to current user details, but the affiliations could have different users for the same company. How could I set user for each affiliation?
Update: I have added
Set<Affiliation> affiliations = company.getAffiliations();
Iterator<Affiliation> iterator = affiliations.iterator();
while (iterator.hasNext()) {
Affiliation existingAffiliation = iterator.next();
Long userId = existingAffiliation.getUserId();
User user = userRepository.findOne(userId);
existingAffiliation.setUser(user);
}
before
Company updatedCompany = companyRepository.save(company);
This helped to resolve the issue, but I am not sure if this is the correct way of doing, any thoughts?