I'm developing a spring mvc webapp with spring data and hibernate.
I've an entity composed by a boolean field and by an Integer field.
At beginning the boolean field is false and Integer field is null.
When boolean field become true I need to assign to the Integer field a unique value equals to MAX(seq) +1
To do it, I write my service method in this way:
@Override
public synchronized Obj save(Obj entry) {
if (entry.getBool() && entry.getSeq() == null){
Integer seq = objRepository.getLastSeq();
if (seq == null){
seq = 1;
}
entry.setSeq(seq);
}
return entry.save(entry);
}
And in my Reposiroty:
@Query("select MAX(seq)+1 FROM Obj")
Integer getLastSeq();
I put synchronized keyword to service method in order to be sure that only a thread at a time can get an unique MAX+1 number.. but I'm not sure if it works in all situation and if it is the right way.
Can I be sure that it guarantee unicity of seq?
Thank you Marco