Search code examples
morphia

How to ignore the `@PostPersist` when saving a model in morphia?


I have a model which has a method annotated with @PostPersist:

@Entity
class User extends Model {
    private String name;
    // getter and setter
    @PostPersist
    public void _postPersist() {
        // do something
    }
}

Now when I save a user, the _postPersist() method will be called automatically.

But now I have to save a user and ignore the _postPersist() method temporarily, is there any way to do this?


Solution

  • What about

    @Entity
    class User extends Model {
        private String name;
        private transient boolean ignorePostPersist = false;
        public User ignorePostPersist() {ignorePostPersist = true; return this;}
        public void ignorePostPersist(boolean b) {ignorePostPersist = b; return this;}
        // getter and setter
        @PostPersist
        public void _postPersist() {
            if (ignorePostPersist) return;
            // do something
        }
        public void saveWithoutPostPersist() {
            ignorePostPersist = true;
            try {
                save();
            } finally {
                ignorePostPersist = false;
            }
        }
    }
    ...
    User user = ...
    user.saveWithoutPostPersist();