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();
}
}
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.");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With