Skip to content
Advertisement

JPA ManToMany association and insert, retrieve data with Spring Data Repository

I need to setup many to many relationship between 2 entities, namely Project and Articles. The use case is a project that can be linked to many articles which are related. So does each article will be linked to various projects. I am using Spring data repository in my project and having trouble persisting and retrieving this relationship with the project and articles.

JavaScript

Article entity

JavaScript

ProjectArticles join table entity. I have created it to resolve table creation issue in hibernate.

JavaScript

Here are the spring data repositories.

JavaScript

Ideally, I want to use repo in service like below.

JavaScript

But things do not work. When I add an existing article to a project and save (update) it, in the relation table (“project_articles”) new row tries to enter but without a project id and I get an exception.

What am I doing wrong here? Is it possible the way I designed the entities?

Advertisement

Answer

The main idea of CascadeType.PERSIST (involved in CascadeType.ALL you use) is to create entity instances, set necessary two-side relations (Project -> Articles, Article -> Projects) and only then save to a database. If you save all projects then articles are saved implicitly due to CascadeType.PERSIST and entity relations

Try this

JavaScript
Advertisement