Skip to content
Advertisement

JPA – Adding and Removing elements in List with ElementCollection

I keep a list of Strings in SQL as @ElementCollection, my main usage is similar to a Queue:

  1. fetch it from the database
  2. run some calculations
  3. remove the first element and insert a new element to the end of the list:

this.measurements.remove(0); this.measurements.add(measurement);

  1. save it to the database

The problem with the current implementation is that removing the first element updates the index of all elements in the list (items_order column) which is very bad for performance… Is there any other way to do this? perhaps is it possible to have a running index (items_order column) so order will be kept but not position in list?

Example:
left to ‘:’ is the index of the element and to the right is the element itself.
[0:”a”, 1:”b”, 2:”c”]

After Calculation the following will be inserted to the database:

[0:”b”, 1:”c”, 2:”d”] – all element indexes have been updated (bad performance)

Possible solution which i’m not sure if possible to implement:

[1:”b”, 2:”c”, 3:”d”] – all elements keep the same order id (still ordered)

My entity:

JavaScript

Advertisement

Answer

What I ended up doing was creating an entity of my own instead of using annotations to create the fields table, this is the Store entity:

JavaScript

this is the Item entity which the store will hold a list of:

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