public Map<String, String> saveEntityData(String entityName, Map<String, String> fieldValues) { Map<String, Data> oldRecord = new HashMap<String, Data>(); long id; String oid = fieldValues.get(ID); if (oid == null) { // entity "insert" Data data = new Data(); data.setAttributeName(ID); data.setFieldValue("0"); data.setEntityId(0); data.setEntityName(entityName); id = getMaxLogicalId(entityName) + 1; // needs to be max of logical ids in case of import foreign ids data.setEntityId(id); data.setFieldValue("" + id); data = save(data); fieldValues.put(ID, "" + id); } else { // entity "update" id = Long.valueOf(oid); List<Data> list = list(entityName, id); for (Data data : list) { oldRecord.put(data.getAttributeName(), data); } } List<Data> adds = new ArrayList<Data>(); List<Data> deletes = new ArrayList<Data>(); for (Map.Entry<String, String> me : fieldValues.entrySet()) { String newValue = me.getValue(); Data oldValue = oldRecord.get(me.getKey()); if (oldValue == null) { Data newData = new Data(); newData.setAttributeName(me.getKey()); newData.setEntityId(id); newData.setEntityName(entityName); newData.setFieldValue("" + me.getValue()); adds.add(newData); } else if (newValue != null && !newValue.equals(oldValue.getFieldValue())) { oldValue.setFieldValue(newValue); adds.add(oldValue); } } for (Map.Entry<String, Data> me : oldRecord.entrySet()) { if (fieldValues.get(me.getKey()) == null) { deletes.add(me.getValue()); } } for (Data data : deletes) delete(data); for (Data data : adds) save(data); return fieldValues; }
public Data mapObject(Cursor cursor) { Data data = new Data(); data.setId(cursor.getInt(0)); data.setEntityName(cursor.getString(1)); data.setAttributeName(cursor.getString(2)); data.setEntityId(cursor.getLong(3)); data.setFieldValue(cursor.getString(4)); return data; }