Skip to content
Advertisement

How to create LinkedList of JPA entities

I have a scenario where I need to create an entity which has references to list of predecessors and list of successors. when a request is received, I need to create entity like below:

Request:

My new entity “task2” should now be created as below in DB.

While saving task2 with previous as task1 and next as task3, I also would like to update task1’s next as task2 and task3’s previous as task1.

I am struggling to come up with a JPA entity relationship for the above scenario.

Update: Below is the the code how I am trying to save the entities.

I am updating all the entities together using saveAll, but the return saved list coming as empty. I do not understand why. Any suggestions on where I am going wrong? I am doubting my entity relationship, may be I have defined relation wrong.

Update 1: I have tried to maintain the relationship of one another through mappedBy, that way the relation will be implied and I dont need to update all the entities.

Here is how I am now saving it

I am able to now save the new entity with its predecessors and the successors can be implied from the table as below

Predecessor - Successor - relation

Advertisement

Answer

In title you mention LinkedList but in your entity the relationship is set ManyToMany so that successors and predecessors an joined to your entity in a “flat” manner. I prepared my answer according to this ManyToMany approach but it is easily applied to OneToOne approach that is more like LinkedList implementation.

I think that you are missing cascade and maybe not correctly setting both sides of relationship. See my simplified and “synchronized” (your naming was a bit confusing) example:

Task (was Entity)

Test it

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement