javanetbeanspersistencejavadb

What the best way to persist data in Java application without SQL or any Database Sever?


I wants create a desktop app that need to store data. This app can be used in various pc's. So, I don't want install sql server and more applications to make this. I want just create a file with all data that is stored, making backup easier and have a fast installation. I thought use a JSON or XML file, or Excel (.xmls), but this appears hard to execute a searchs, or other operation. So, before implements this I want a opinion.


Solution

  • You can use com.typesafe.config or SQLite. It depend on data, that you must store. Another solution is to serialize your data class to XML\JSON with GSON or xstream

    Gson example:

    public static class Entity {
        volatile int id;
        String name;
        transient long random;
    
        public Entity(int id, String name) {
            this.id = id;
            this.name = name;
        }
    }
    //Create new entity
    Entity entity = new Entity(100, "name");
    entity.random = 1234;
    
    //Serialize to JSON. Then you can save string to file
    String json = gson.toJson(entity); // {"id":100,"name":"name"}
    // On application start you can deserialize your entity from file
    Entity read = gson.fromJson(json, Entity.class);