How to lock row in mysql that access from 2 difference instance application?

Viewed 17

I have a problem with mysql query i am using SELECT ... FOR UPDATE to locking a row in my table data source so that two instance application cannot get the same row at the same time. But when i test with jmetter to hit my program, sometime mysql return the same value.

The goal is i want to select example : enter image description here

i have a table that have id | name | last_seq so when my 1st instace application select that row will add 100 to last_seq. so the value for that rows now is 1 | opr_sequece | 100 and when my 2nd instance application select that row will add 100 to last_seq. so the value for that rows after selection from 2nd instance is 1 | opr_sequence | 200.

but when i run, sometimes 2 instance applications get same value and update the same value too to table.

i do SELECT ... FOR UPDATE but it sill happend. Please help me

UPDATE

public synchronized String constructTraceNo(){
    if(counter % 100 == 0){
        OprSeq oprSeq= oprSeqRepo.findByNm("opr_sequence");
        //update to repository
        counter = oprSeq.getLastSequence();
        oprSeq.setLastSequence(counter+100);
        oprSeqRepo.save(oprSeq);
    }else if(counter == 999999){
        OprSeq oprSeq= oprSeqRepo.findByNm("opr_sequence");
        counter = 0;
        oprSeq.setLastSequence(counter+100);
        oprSeqRepo.save(oprSeq);
    }
    counter+=1;
    return padding(String.valueOf(counter),6,"0",0);
}

OprSeq oprSeq= oprSeqRepo.findByNm("opr_sequence"); this will select the row and the update below that selection.

1 Answers

There are many ways that can generate the same result. Some of them are:

  • Use autocommit instead of explicit transactions
  • Don't update the record but only selecting it (for example update the record only if a condition is satisfied)
  • Try catch the code so that in case of a failed update there is no rollback
  • If some code reset values or decrement values

You should investigate the different possibilities or post an updated question with the full code.

Related