Increment 1 to each item in a list and save it in the database

1

The problem is this: I have a table in the database with a field position which receives integer values, then I load a list with the data of my table, now I need that when inserting a new record in the position 1 and if position 1 already exists in the database, go to number 2 and if there is 2, go to 3 and so on. All this with java.

public String accionRecorre() throws Exception {
 lstSecciones=adminConfiguracionAsociadosDao.getLstMostrarSecciones();
 int indice=Integer.parseInt(request.getParameter("tfIndex"));
   for(int i=0; i<lstSecciones.size(); i++){
    posInicial=lstSecciones.get(i).getIndex();
        if(indice==posInicial){
           posInicial++; //es en esta parte donde no sé cómo condicionar      
            }

 adminConfiguracionAsociadosDao.insertarSeccion(idAsociado,nombre, visible,    posInicial, estado); 

 return SUCCESS;
}
    
asked by Jesus Ayala 10.05.2018 в 22:24
source

2 answers

1

Would it be feasible to retrieve that BD list already sorted by that field position? And second question, what version of Java are you working with? (I'll assume that Java 8, but if it's an earlier version, it's just a matter of you adjusting the code)

If you can not get it back in order, you order it yourself with

lstTmp = lstSecciones.stream().sorted(Comparator.comparing(<TuClase>::getIndex)).collect(Collectors.toList());

Once you have the list sorted, you can proceed to process it:

int i = 1;
for(<TuClase> elem: lstTmp) {
    if (elem.getIndex() == i) {
        elem.setIndex(++i);
        //Cualquier otra acción que debas hacer
    }
}

I hope it helps you

    
answered by 11.05.2018 в 07:34
0

Disclaimer: This should go as a comment, but since I do not have the reputation level yet, I put it here as a solution to the same problem that I had to solve once.

Having a table TABLA_A and knowing the maximum possible number of records that it can contain at any time, you can make a JOIN with another TABLA_B containing the possible values and return only those that are in the TABLA_B and not in the TABLA_A , which would help you to locate the first " hollow " between rows.

In the following code, my database is oracle, I use the table DUAL to generate the values from 1 to :LIMITE , where I set an X value that exceeds the maximum number of records that I consider the table TU_TABLA currently contains. The advantage of this is that the database itself is responsible for locating the gap and not the program that must travel row by row to locate where to insert the new value.

SELECT A.ID AS OCUPADO, B.POSICION AS HUECO_DISPONIBLE
FROM TU_TABLA A
RIGHT OUTER JOIN (
SELECT LEVEL AS POSICION
    FROM DUAL 
CONNECT BY LEVEL <= :LIMITE
) B ON A.ID = B.POSICION
WHERE A.ID IS NULL
AND ROWNUM = 1;

With the ROWNUM what I do is that I return only the first row of the set of available values.

    
answered by 11.05.2018 в 16:42