Jsondb / jsondb-core

JsonDB a pure java database that stores its data as Json Files

Home Page:http://www.jsondb.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Simple collections as part of Documents

opened this issue · comments

Hello,

I have a simple bean:

@Data
@Document(collection = "beans", schemaVersion = "1.0")
public class Bean {
  @Id
  private String id;
  
  private List<String> stuff;

  public Bean() {
    this.id = UUID.randomUUID().toString();
  }
}

and some database class

public class Database {
  private final JsonDBTemplate jsonDBTemplate = new JsonDBTemplate...

  public Database() {
    if (!jsonDBTemplate.collectionExists(Bean.class) {
      jsonDBTemplate.createCollection(Bean.class);
      Bean bean = new Bean();
      bean.setStuff(Arrays.asList("A", "B"));

      jsonDbTemplate.upsert(bean);
    }    
  }
}

So in json, bean comes as:

{"id":"8b38034d-77d6-443f-8f00-4d757f26658f","stuff":null}

Is the saving of basic collections inside of documents not supported? Is there a workaround for that?

Using version: 1.0.36

Thank you,
oiale

Hi @oiale

Arrays.asList("A", "B") returns a object of type Arrays$ArrayList```

Arrays.asList returns a List implementation, but it's not a java.util.ArrayList. It happens to have a classname of ArrayList, but that's a nested class within Arrays - a completely different type from java.util.ArrayList

Also JsonDB uses XMLEncoder internally to create a deep copy of objects before processing them. However Arrays$ArrayList does not serialise properly, thats probably because XMLEncoder requires it to be a valid JavaBean, meaning among other things it should have a default public constructor which Arrays does not have

So the way you are using it, its not going to work. To workaround this issue I suggest you create a proper java.util.List and then set it into the bean:

List<String> stuff = new ArrayList<String>(Arrays.asList("A", "B"));
bean.setStuff(stuff);

This should work, i added a unit test to test this and it passes just fine.

The latest build on Maven Central is: 1.0.64

@FarooqKhan
Thank you, the issue is resolved. Do you have a wiki that you could put this on?