morphia icon indicating copy to clipboard operation
morphia copied to clipboard

@PrePersist of parent class called on embedded values that do no inherit any @PrePersist methods

Open zenbones opened this issue 2 years ago • 5 comments

With 2.3.0 I have a base class...

pubic abstract class Durable<I> {

  @Id
  private I id;

  @Override
  public I getId () {

    return id;
  }

  @Override
  public void setId (I id) {

    this.id = id;
  }

  @PrePersist
  public void prePersist (final DBObject dbObj) {

  ... stuff I need to do ...
  }
}

...and an entity that extends the base class...

@Entity(value = "something", useDiscriminator = false)
public class Something extends Durable<ObjectId> {

  @Property("child")
  private Child child;

  public Child getChild () {

    return child;
  }

  public void setChild (Child child) {

    this.child  = child;
  }
}

...and finally the child...

@Entity
public class Child {
...
}

So, Something has the @PrePersist method inherited from Durable, and Child has no pre persist, but during an update executed to create a new Something the prePersist method from Durable is called with Child as a target, from dev.morphia.mapping.codec.pojo.ClassMethodPair : 61, which fails with ...

Error in process java.lang.IllegalArgumentException: object is not an instance of declaring class

...probably because Child is not a Durable and should not be pre-persisted.

zenbones avatar Jan 11 '23 23:01 zenbones

This code path is kicked off by dev.morphia.query.updates.SetOnInsertOperator: 63, which calls the encode for each key/value, which ends up calling the lifecycle methods for each entry, evidently using the parent's registered pre-persist methods. So it calls the parent's method with the instance of the field as the method target (via reflection), and the class of the target (the class of the field) does not contain any such method.

zenbones avatar Jan 12 '23 01:01 zenbones

If you could put together a reproducer I'd be happy to take a look and see.

evanchooly avatar Jan 12 '23 12:01 evanchooly

seethis.zip

Maven project with an executable Test class that reproduces the issue.

zenbones avatar Jan 12 '23 20:01 zenbones

This seems like a bug to me, and I can understand that you're busy, and I should be willing to help rather than just submit. If I can get your confirmation that this behavior is unexpected, given the test case I've included, I'd be willing to dive in and try to find a resolution. I'd just like to know that I haven't misread or misconfigured so I'm not learning a code base to try and resolve something that isn't a bug at all.

zenbones avatar Jan 19 '23 19:01 zenbones

I was able to fix the bug and place a pull request.

zenbones avatar Jan 21 '23 07:01 zenbones