Spring Cassandra with optimistic lock, the entity immediately saved after deleting by the partition key will missing

36 Views Asked by At

Here is the related information:

  1. springboot 2.7.4
  2. Spring Cassandra with optimistic lock (@Version)
  3. clear by a partitionKey
  4. insert an entity with the (partitionKey, clusterKey)
  5. cannot find the entity in 4
  6. sleep 500ms and save another entity
  7. can find the entity in 6

But when I removed the @Version annotation, 5. can fine the entity in 4

Can someone explains it? Thanks.

demo:

@Data
@Builder
@PrimaryKeyClass
public class CommandTestPK {

    @PrimaryKeyColumn(name = "partition_key", ordinal = 0, type = PrimaryKeyType.PARTITIONED)
    private String partitionKey;

    @PrimaryKeyColumn(name = "clustered_key", ordinal = 1, type = PrimaryKeyType.CLUSTERED)
    private String clusteredKey;

}

@Data
@Builder
@Table("command_test")
public class CommandTestPO {

    @PrimaryKey
    private CommandTestPK commandTestPK;

    @Column("command")
    private String command;

    @Version
    @Column("version")
    private Integer version;
}

@Repository
public interface CommandDAO extends CassandraRepository<CommandTestPO, CommandTestPK> {

    @Query("delete from command_test where partition_key  = ?0")
    void clearAll(String partitionKey);

    @Query("select * from command_test where partition_key  = ?0")
    List<CommandTestPO> findAll(String partitionKey);

}

run:

        String partitionKey = "partitionKey";

        commandDAO.clearAll(partitionKey);
        log.info("clearAll");

        CommandTestPO commandTestPO = CommandTestPO.builder()
            .commandTestPK(CommandTestPK.builder()
                .partitionKey(partitionKey)
                .clusteredKey(UUID.randomUUID().toString())
                .build())
            .command("setCommand0")
            .build();
        commandDAO.save(commandTestPO);
        log.info("save={}", commandTestPO);
        List<CommandTestPO> commandTestPOList = commandDAO.findAll(partitionKey);
        log.info("commandTestPOList={}", commandTestPOList);

        Thread.sleep(500);

        commandTestPO = CommandTestPO.builder()
            .commandTestPK(CommandTestPK.builder()
                .partitionKey(partitionKey)
                .clusteredKey(UUID.randomUUID().toString())
                .build())
            .command("setCommand1")
            .build();
        commandDAO.save(commandTestPO);
        log.info("save={}", commandTestPO);
        commandTestPOList = commandDAO.findAll(partitionKey);
        log.info("commandTestPOList={}", commandTestPOList);

How to avoid this issue while using optimistic locking

0

There are 0 best solutions below