Search code examples
mongodbmorphia

@PrePersist not invoked for referenced objects?


I have a recursive data structure like this:

@Entity
class Node {
    @Id
    private Long id;

    @Reference
    private List<Node> children;

    ...

    @PrePersist
    void populateSequentialId() {
        // query data store for highest id and increment, then set the id field
    }
}

Then I populate a tree of Node objects, all without ids set. The depth varies, but usually it is about 3 levels deep.

When I call save() on an object without children, it works. The id is generated and set, and object is saved. That means the @PrePerist was invoked on that entity as expected.

But for entities that are in the Referenced list @PrePersist is never invoked, and the save call fails due to a null @Id field.

Is this a bug in Morphia or I'm having the wrong expectations?


Solution

  • You need to persist every document on its own.

    So if A references B:

    1. Persist B
    2. Persist A, so you have B's _id for the reference

    Otherwise the operation will fail.