I would like to generate unique id for entity and store the entity in Cassandra database (only if entity with generated id does not exist already).
After id generation I check in db if there is any entity with the same id. If not, then the entity is saved. Sample code from MyService class:
synchronized (MyService.class) {
do {
id = generateId();
} while (myDao.find(id) != null);
sampleObject.setId(id);
myDao.create(sampleObject);
}
In MyDao to save entity I'm using:
cassandraOperations.insert(sampleObject);
What is the best practice to ensure that already generated id does not exist in database? I feel that this synchronize block is not the most efficient solution. Or maybe there is any other way in which I can ensure that entity is inserted only if there is no entity with the same id in database?