使用db.command触发挂钩

时间:2015-02-18 10:17:12

标签: orientdb

  public class Hooks {

     public static void main(String[] args) {
        ODatabaseDocument db = new ODatabaseDocumentTx("remote:localhost/New");
        MyHook hook = new MyHook();

        try {
           db.open("admin", "admin");
           db.registerHook(hook);
           db.command(new OCommandSQL("create class Account")).execute();

           db.getMetadata().getSchema().reload();

           ODocument accountR = new ODocument("Account");
           accountR.field("type", "facebook");
           accountR.save();

           db.command(new OCommandSQL("insert into Account set type = 'twitter'")).execute();

        } finally {
           db.unregisterHook(hook);
           db.close();
        }
     }

     private static class MyHook extends ODocumentHookAbstract {

        public MyHook() {
           setIncludeClasses("Account");
        }

        @Override
        public ORecordHook.DISTRIBUTED_EXECUTION_MODE getDistributedExecutionMode() {
           return ORecordHook.DISTRIBUTED_EXECUTION_MODE.SOURCE_NODE;
        }

        @Override
        public ORecordHook.RESULT onRecordBeforeCreate(ODocument iDocument) {
           System.out.println("before create : " + iDocument.field("type"));
           return ORecordHook.RESULT.RECORD_NOT_CHANGED;
        }
     }
  }

输出结果为:

before create : facebook

这意味着钩子只在doc.save()中触发。

有没有办法用db.command(...)触发它?

(尝试删除时遇到同样的问题。只有doc.delete()会触发钩子)

由于

1 个答案:

答案 0 :(得分:1)

OCommandSQL命令由服务器执行。如果您使用plocal连接,您会看到它按预期工作。 要执行(java)钩子服务器端,必须在那里注册,请参阅documentation。另请注意,您可以使用Dynamic Hooks

BTW欢迎来到stackoverflow:)