4

Spring-data-mongodb is trying to add createdDate to a null object and fails to do so. How do I configure spring audit to ignore null objects so it does not try to add audit fields to it?

I have an abstract class with all the audit info. Two classes (A,B) extend this abstract class and one of those two classes (A) has a reference to the other class (B) (that can be nullable). If I try to save an object of A with a null reference to B. It all fails because spring is trying to add audit info to the B null reference.

public abstract class AA {
    @Id
    private String id;
    @Version
    private Long version;
    @CreatedDate
    private LocalDateTime createdDate;
    @LastModifiedDate
    private LocalDateTime LastModifiedDate;
}

public class A extends AA {
   private String name;
   @Nullable
   private B b;
}

public class B extends AA {
   private String name;
}

public class ControllerA {

    private AMongoRepository aMongoRepo;

    public void saveSomeA(String name) {
        A a = new A();
        a.setName("Some Name");
        a.setB(null);
        aMongoRepo.save(a); // <-- Fails can not set createdDate on B null
    }
}

The error message I get is the following.

org.springframework.data.mapping.MappingException: Cannot lookup property B A.b on null intermediate! Original path was: b.createdDate on A.

A quick google search brought me to jira.spring.io, which is the same issue I am having.

Any idea on how to cleanly handle this issue? Maybe move from inheritance to composition? Or should I just be patient an wait on the new version?

0 Answers0