在Grails自定义事件侦听器中保存实体

时间:2015-03-01 16:39:45

标签: grails

我正在编写Grails 2.3.7应用程序,我在那里有2个域实体:CommentEvent。保存在数据库中的每个新Comment都应生成并保留相应的Event。为此,我尝试在PostInsertEvent中拦截AbstractPersistenceEventListener

class MyPersistenceEventListener extends AbstractPersistenceEventListener {

    public MyPersistenceEventListener(Datastore ds) {
        super(ds)
    }

    @Override
    protected void onPersistenceEvent(AbstractPersistenceEvent event) {
        Event.withTransaction {
            new Event(text: "New comment posted").save()
        }
    }

    @Override
    boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return eventType.isAssignableFrom(PostInsertEvent)
    }
}

这种方法不起作用:onPersistenceEvent被调用,但新的事件记录不会出现在数据库中。是否可以在perstence事件监听器中保存另一个实体,或者有更好的方法来执行此操作吗?

1 个答案:

答案 0 :(得分:0)

最后,我设法将其保存在不同的主题中:

class MyPersistenceEventListener extends AbstractPersistenceEventListener {

    final def eventQueue = new DataflowQueue()

    public MyPersistenceEventListener(Datastore ds) {
        super(ds)
        Dataflow.operator(inputs: [eventQueue], maxForks: 10) { event ->
            Event.withTransaction {
                event.save()
            }
        }
    }

    @Override
    protected void onPersistenceEvent(AbstractPersistenceEvent event) {
        if (event.entityObject instanceof Comment) {
            eventQueue << new Event(text: "New comment posted")
        }
    }

    @Override
    boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return eventType.isAssignableFrom(PostInsertEvent)
    }
}

但我仍然怀疑这是否是正确的解决方案......