我正在编写Grails 2.3.7应用程序,我在那里有2个域实体:Comment
和Event
。保存在数据库中的每个新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事件监听器中保存另一个实体,或者有更好的方法来执行此操作吗?
答案 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)
}
}
但我仍然怀疑这是否是正确的解决方案......