javahibernateeventscallbackplayframework-1.x

Play! Behavior for after save model operation


I want to implement a behavior that insert a row in a table after some models saves. My current solution in short is this: (This is just an example of my code so please do not comment on the correctness of the database or the descriptor model).

DescriptionListener.java

public class DescriptionListener {
    @PostPersist
    public void onPostPersist(Object entity) {
        Description description = new Description("INSERT");
        description.save();
    }

    @PostUpdate
    public void onPostUpdate(Object entity) {
        Description description = new Description("UPDATE");
        description.save();
    }
}

Description.java

@Entity
@Table(name="DESCRIPTION")
public class Description extends GenericModel {
    @Id
    @GeneratedValue
    @Column(name="ID")
    public Long id;
    @Column(name="INFO")
    public String info;

    public Description(String info) {
        this.info = info;
    }       
}

A callback method must not invoke EntityManager or Query methods!

Now i think the save() method is a Query method so i cannot use in callback functions (but it works the same in my case) and my question is:

How can I implement a behavior of the same type and save a model on after save of another model?

Is there anything that can help me in Play?

I follow this documentation: Entity listeners and Callback methods


Solution

  • Play's JPA support implemented with the help of bytecode enhancements and JPAPlugin

    Also as you knew, each entity extends some classes like; JPABase.java

    On CRUD operations; JPABase broadcasts an event to Play's plugin system eg: JPASupport.objectUpdated.

    So you can write a custom PlayPlugin to catch these events and make some other changes.

    However IMHO you should follow the hibernate's suggestion and make your changes in new transaction. Playing with attached entities after these kind of lifecycle events is always a burden. Think async and make your changes in another transaction.