jeudi 28 juillet 2016

Prevent Jackson @JsonUnWrapped to introduce duplication

I am developping an application architectured this way.
A BaseObject contains the following fields :

public class BaseObject {
    private String id;  
    private Instant creationDate;  
    private String createdBy;  
    private Instant lastEditionDate;  
    private String lastEditBy;  
    private Instant deletionDate;  
    private String deletedBy;
}

Every class extends this BaseObject so I end up with two POJOs like this :

public class Pojo1 extends BaseObject {
    private SubPojo1 subPojo1;
    private SubPojo2 subPojo2;
}

public class Pojo2 extends BaseObject {
    private SubPojo3 subPojo3;
    private SubPojo4 subPojo4;
}

These two POJOS do not have a functional relationship. They are constituted of SubPojo which group fields in a functionnal way.

Here come my problem. My application is sending data to a BI app by JSON. The BI app need to get the POJO to a "flat" format and I want to exclude the BaseObject fields.

So i came up with this :

public class FlatPojo1 extends Pojo1 {
    @Override
    @JsonIgnore
    public String getId() {
        return super.getId();
    }
    /* Override every getter of BaseObjet */

    @Override
    @JsonUnwrapped
    public SubPojo1 getSubPojo1 {
        return super.getSubPojo1();
    }
    /* Override every getter of Pojo1 */
}

My solution is working, the BI app get the data properly formatted and I can still handle my objects with sub-objects.

The thing that disturb me is the code duplication. For each flat object, I have to override every getter of my BaseObject. I would like not to.

Java does not allow multiple heritage so I can not make an abstract class that @JsonIgnore every BaseObject field and also extending my Pojo1.

I tried to come with an interface like this :

public interface BaseObjectInterface {
    String getId();
    Instant getCreationDate();
    // etc
}

My BaseObject now implements BaseObjectInterface, everything is ok.Then the plan is to create a FlatData interface that will @JsonIgnore the BaseObject fields and every FlatPojo will implements this interface. I came up with this :

public interface FlatData extends BaseObjectInterface {
    @Override
    @JsonIgnore
    default String getId() {
        BaseObjectInterface.super.getId(); // Error
    }

I get an error message telling me that I can not call an abstract method. And I can not make a default getId() method in my BaseObjectInterface because such would require an id field and every field in an interface are static.

I can not find a way to avoid duplicating all theses @JsonIgnore. Is there any way to do it ?
Thank you for your help.

Aucun commentaire:

Enregistrer un commentaire