Home > Enterprise >  Problem when persisting entities that have @OneToMany relations
Problem when persisting entities that have @OneToMany relations

Time:02-24

I have to create a simple application with Spring and Postgres. I have some entities that are in relations, such is Job, Company, ProgrammingLanguage. A Job entity has a @ManyToOne relation with Company, and a @OneToMany relation with ProgrammingLanguage. I need to persist a lost of each of these 3 entities in the corresponding tables in DB, especially Job. After I create the objects Company and ProgrammingLanguage I persist them into DB using their repositories and everything is fine. Then I set these objects as attributes of the Job entity and persist that too. I run my application and for the first and second job from the list I must persist everything works fine, they are added to the DB. But when it comes to the third job the application crashes with an error that says:

2022-02-24 13:56:00.838  WARN 8364 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 23505

2022-02-24 13:56:00.839 ERROR 8364 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: duplicate key value violates unique constraint "uk_gi5d5wf8tux7hmiwtk9nhql9k"

Detail: Key (programming_languages_id)=(30) already exists.

Also I have the debugger on and print details about each ProgrammingLanguage, and each time the application stops at that id=30 of the ProgrammingLanguage record. This is the image with Output console from Netbeans

And the piece of code for creating and persisting entities is this:

Has anyone idea where does this duplicate id comes from in ProgrammingLanguage entity? Isn't it supposed to be a sequence that deals with entities' Ids?

CodePudding user response:

I believe, your problem is that a programming language entity exists twice with ID 30 in your DB, isn't it?

CodePudding user response:

Can you show us the entity class for ProgrammingLanguage and how are you inserting into the DB?

CodePudding user response:

You need to study a bit on persistence and understand how it works. Entities that are related together need to be persisted carefully. As a hint for your problem - You should save the top most entity only and that will save all related children entities. The error you are getting is because the programming language entity has alrady been saved (you saved it manually), and it is also being saved as part of the parent entity (as part of your third job)

CodePudding user response:

First, you have to post your Entity code.

but with a high probability, the database will already have that value.

  • Related