The database (Cassandra) does not allow specifying a default value when adding new columns. New columns are therefore null
for every row.
Now, we added a flag to our entity (which might get more entries in the future):
enum UsageFlag {
OTHER,
SPECIAL_VALUE,
}
We also added a ReadingConverter:
@ReadingConverter
public class UsageFlagReadingConverter implements Converter<String, UsageFlag> {
@Nonnull
@Override
public UsageFlag convert(String source) {
return source == null
? UsageFlag.OTHER
: UsageFlag.valueOf(source);
}
}
It should basically treat null
as UsageFlag.OTHER
while parsing any other non-null value as an enum member.
However, this does not work since according to the Spring docs, the convert method of the Converter is only called if the value is not null
. Because of this, the field of that entity remains null
if it is null
in the database. It works fine if (and only if) there is a value. Since the entire column is null when creating it, this completely defeats the purpose of the ReadingConverter
.
Cassandra does not seem to support setting a value for every row (like UPDATE foo SET flag='OTHER' WHERE True
), so this seemed like a good option. We wanted to avoid touching every row in the database manually.
Is there any way we can use Spring to help in this situation? Or is there a way to solve this using CQL or Cassandra?
Edit: Some more context on the setup:
public interface FancyEntityRepository extends MapIdCassandraRepository<FancyEntity> {
}
public class FancyEntity {
@PrimaryKeyColumn(name = "id", ordinal = 0, type = PrimaryKeyType.PARTITIONED)
private string id;
private UsageFlag usage;
// other columns omitted
// getters and setter omitted for this example
}
// Somewhere in a service:
FancyEntity fe = fancyEntityRepository.findOne("1");
System.out.println(fe.getUsage());
But I don't think that the behaviour of the converter is cassandra-specific.
The table was created and then altered this way:
CREATE TABLE FancyEntity (
id TEXT,
-- other columns omitted
PRIMARY KEY (id)
);
ALTER TABLE FancyEntity ADD (
usage TEXT
);
Cassandra Docs on ALTER TABLE and a related SO question about altering tables with a default value.