Spring Data JDBC: how do I update reference of Entity to another Entity?

109 views Asked by At

I have 2 entities: Manager and Project. I want to save them separately and, when time comes, update the link from Manager to Project. But this doesn't work.

Here is the code:

@Test
void updateProjectInManager() {

Manager oldManager = new Manager();
Manager savedOldManager = managerRepository.save(oldManager);

Project newProject = new Project();

savedOldManager.setProject(newProject);
managerRepository.save(savedOldManager); //it works
}


@Test
void updateProjectInManagerIfProjectExists() {
Manager oldManager = new Manager();
Manager savedOldManager = managerRepository.save(oldManager);

Project newProject = new Project();
Project savedProject = projectRepository.save(newProject); //it breaks everything

savedOldManager.setProject(savedProject);
managerRepository.save(savedOldManager); //it fails as it tries to insert savedProject again
}

1st test works. 2nd test fails with "Unique index or primary key violation" on table projects.

Actually the error makes sense: looks like Spring is trying to insert entity Project into projects table for the 2nd time and fails as it is already there. But how I can link them otherwise?

Please bear in mind that I am using Spring Data JDBC, not Spring Data JPA.

1

There are 1 answers

2
Jens Schauder On

If you have a repository for both, they both are separate aggregates. References between aggregates must be modelled as simple ids, or better as AggregrateReference wrapping the id. See https://spring.io/blog/2018/09/24/spring-data-jdbc-references-and-aggregates/