Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update in orient db using document api

I am trying to run an upsert using document api but was not able to find any method or easy way to do. Below is the code, every time I run, it inserts a new record everytime

   public class TestUpsert {

   public static void main(String[] args) {
          Object obj = new Object();
          obj.setRpstryId("ABC");
          obj.setObjId("123");
          obj.setObjIdCntxtCd("456");
          obj.setObjNm("XYZ");
          obj.setObjDesc("text");
          obj.setObjTypId("78901");
          createObject(obj);
   }

   public static void createObject(Object obj) {

          try (ODatabaseDocumentTx db = new ODatabaseDocumentTx(
                       "remote:localhost/abc").open("root", "admin");) {

                 ODocument obj = new ODocument("Object");
                 obj.field("rpstryId", obj.getRpstryId());
                 obj.field("objId", obj.getObjId());
                 obj.field("objIdCntxtCd", obj.getObjIdCntxtCd());
                 obj.field("objTypId", obj.getObjTypId());
                 obj.field("objNm", obj.getObjNm());
                 obj.field("objDesc", obj.getObjDesc());
                 System.out.println("Completed");
                 obj.save();                    
                 db.close();
          } catch (Exception exception) {                   
                 exception.printStackTrace();

          }

   }
like image 589
skonka Avatar asked Feb 11 '26 09:02

skonka


1 Answers

You first need to retrieve your document by its ID, which in your case I believe to be ObjId. There are a few ways to query the database.

List<ODocument> result = db.query(
new OSQLSynchQuery<ODocument>("select * from <table name> where ObjId = '" + obj.getObjId() + "'"));

Then check if there is a record, if there is you can update and then call save().

if (result != null and result.size() == 1) {
    // Update here
    ODocument doc = result.get(0);
    doc.field("rpstryId", obj.getRpstryId());
    doc.field("objId", obj.getObjId());
    doc.field("objIdCntxtCd", obj.getObjIdCntxtCd());
    doc.field("objTypId", obj.getObjTypId());
    doc.field("objNm", obj.getObjNm());
    doc.field("objDesc", obj.getObjDesc());
    System.out.println("Completed");
    doc.save();                    
    db.close();
} else {
    System.out.println("Couldn't find the record.");
}
like image 186
Tulio F. Avatar answered Feb 13 '26 04:02

Tulio F.