Search code examples
javajsondeserializationebean

How to update a Java (Ebean) Object from a Json Object


I already know how to create an Object from a Json with the following code :

SomeClass someObject  = Json.fromJson(someJsonNode, SomeClass.class);

I also know how to save() and update() an ebean object.

What I would like to do, is update an existing object from data in a JsonNode, something that would look like this :

SomeClass someObject = fetchMyObjectFromDb();
someObject.updateFromJson(someJsonNode);

or

SomeClass someObject = fetchMyObjectFromDb();
Json.updateFromJson(someJsonNode,someObject);

In my specific case, the object is an Ebean Entity, maybe this can help but I did not find any helper method from Ebean to to that.

My Json.* tools are very similar to Google Gson, but I could not find what I want in there either.

Do I have to code that myself using Java reflexion, or is there an easier way/tool to do just that ?

Edit: I would also be happy with simply a way to update multiple attributes of an Ebean entity. I can't find a simple "set" in the form of myEbeanObject.set("attributeName",value) ?


Solution

  • If anybody is interested, here is what I ended up doing. Small utility method, updates a java object from an other java object of the same class, using java reflection :

    import java.lang.reflect.Field;
    import java.lang.reflect.Modifier;
    
    public <T> void updateObjFromObj(T objToUpdate, T objToUse)
            throws IllegalAccessException {
        Class<?> clazz = objToUpdate.getClass();
    
        while (clazz != null) {
            Field[] fields = clazz.getDeclaredFields();
    
            for (Field field : fields) {
                if (!Modifier.isStatic(field.getModifiers())) {
                    boolean accessible = field.isAccessible();
                    field.setAccessible(true);
                    if (field.get(objToUse) != null) {
                        field.set(objToUpdate, field.get(objToUse));
                    }
                    field.setAccessible(accessible);
                }
            }
    
            clazz = clazz.getSuperclass();
        }
    }
    

    Updates a field only if the new value is not null. Can be used as followed to update an ebean object from Json :

    SomeClass someObjectToUpdate = fetchMyObjectFromDb();
    SomeClass objectToUse  = Json.fromJson(someJsonNode, SomeClass.class);
    updateObjFromObj(someObjectToUpdate, objectToUse);
    someObjectToUpdate.save();
    

    Edit/Update : If you are using this to update ebean objects, you need yo use setters and getters for the change to be persisted into the DB.

    So you can add this before the field loop :

    PropertyAccessor objToUpdateAccessor = PropertyAccessorFactory.forBeanPropertyAccess(objToUpdate);
    

    And then instead of :

    field.set(objToUpdate, field.get(objToUse));
    

    Use :

    objToUpdateAccessor.setPropertyValue(field.getName(), field.get(objToUse));