How to update ManyToMany with extra columns

感情迁移 提交于 2021-02-07 10:30:46

问题


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?

来源:https://stackoverflow.com/questions/52210014/how-to-update-manytomany-with-extra-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!