Sobes.tech
Senior

How to store enumerable values in a string column of a database using a separator and work conveniently with a collection in code?

sobes.tech AI

Answer from AI

Storing enumerable values in a string column separated by a delimiter (e.g., comma) is a common but not the most convenient method. To work with such data easily in code, you can:

  • Store the values as a string with a delimiter, for example: "red,green,blue".
  • When reading from the database, split the string into a collection (list, array) using the split method.
  • When writing to the database, join the collection back into a string using join.

Example in Java:

String stored = "red,green,blue";
List<String> colors = Arrays.asList(stored.split(","));

// For writing back
String toStore = String.join(",", colors);

Disadvantages of this approach:

  • No data integrity control at the database level.
  • Difficult to query by individual elements.

If the database supports array or JSON types, it is better to use them for storing collections.