Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read null as empty set in springdata-cassandra

I use spring-data-cassandra, and have entity like this:

@Table("users")
public class User {

  @Column("permissions")
  @CassandraType(type = DataType.Name.SET, typeArguments = {DataType.Name.TEXT})
  public Set<String> permissions = new HashSet<>(); 
}

In cassandra I have table users with field permissions of type Set. It works fine when I store some values in the set, but when I try to store empty set, it becomes null when I read such entity from the repository.

Is there a way to force spring-data-cassandra to change null to empty HashSet? Or can I somehow add custom reader for this specific property of the entity?

like image 268
amorfis Avatar asked Aug 24 '26 18:08

amorfis


1 Answers

TL;DR;

That's Cassandra's default behavior to return null for empty Collection and Map-typed columns.

Further Read

Cassandra returns null values for lists, sets, and maps, which do not contain any items. This is especially unfortunate when using classes with pre-initialized fields as seen in your question. There's an open ticket (DATACASS-266 - Loading empty collection-typed properties overwrites pre-initialized fields) in the issue tracker - as of now, without comments or votes.

We're not exactly sure whether it's a good idea to skip setting properties or apply some sort of defaulting when dealing with empty (null) collections as this raises follow-up questions what to do when:

  • Creating an instance through constructor creation: A value is required in such case. For property access, we could omit to set the property, for constructor creation we must provide a value.
  • The pre-initialized collection contains items but the one received from Cassandra is null.
  • We assume, the change would be applied, what will happen with already existing code that assumes empty collections default to null.

A possibility to address this behavior could be configuration on MappingCassandraConverter or an extension point to override so users can apply their own empty collection behavior.

like image 117
mp911de Avatar answered Aug 26 '26 13:08

mp911de