/*
(non-Javadoc)

@see
com.impetus.kundera.client.ClientBase#onPersist(com.impetus.kundera.metadata
.model.EntityMetadata, java.lang.Object, java.lang.Object,
java.util.List)
969798
@Override
    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
    {
        // TODO Auto-generated method stub
        // handle persist object
        PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(
                persistenceUnit);
        String clientName = puMetadata.getProperty(DATA_CLIENT).toLowerCase();

        List listEntity = new ArrayList<>();
        listEntity.add(entity);

        SparkDataClient dataClient = SparkDataClientFactory.getDataClient(clientName);

        dataClient.persist(listEntity, entityMetadata, this);
    }
865009
public void addListener(SettingsEntityListener settingsEntityListener) {
    RunAsSystemAspect.runAsSystem(
        () ->
            entityListenersService.addEntityListener(
                entityTypeId,
                new EntityListener() {
                  @Override
                  public void postUpdate(Entity entity) {
                    settingsEntityListener.postUpdate(entity);
                  }

                  @Override
                  public Object getEntityId() {
                    return getEntityType().getId();
                  }
                }));
  }
922926
private void parsePersistence(Map<Object, Object> props) {
        parseKeepAliveEnabled(props);
        if (isKeepAliveEnabled()) {
            parseMaxPersist(props);
        }
    }
339503
private static void forEachFields(SQLiteModelMethod method, OnPropertyListener listener) {
		for (SQLProperty item : method.getEntity().getCollection()) {
			listener.onProperty(item);
		}
	}
602743
private void onParseRelation(Object entity, final PersistenceDelegator pd, EntityMetadata targetEntityMetadata,
            Object relationEntity, Relation relation, boolean lazilyloaded, Map<Object, Object> relationStack)
    {
        parseRelations(entity, getEntity(relationEntity), getPersistedRelations(relationEntity), pd,
                targetEntityMetadata, lazilyloaded, relationStack);

        // if relation ship is unary, no problem else we need to add
        setRelationToEntity(entity, relationEntity, relation);
    }
956732
private <T> void doInterceptBeforeUpdate(List<Object> tList, String setSql, List<Object> setSqlArgs) {
		for (DBHelperInterceptor interceptor : interceptors) {
			boolean isContinue = interceptor.beforeUpdate(tList, setSql, setSqlArgs);
			if (!isContinue) {
				throw new NotAllowQueryException("interceptor class:" + interceptor.getClass());
			}
		}
	}
562365
byte[] loadPersist() {
    // 00       assert: not written yet
    // 01       assert: load-after-delete
    // 10       expected; read
    // 11       assert: load-after-delete
    assert isPersisted();
    try {
      byte[] res = H2O.getPM().load(backend(), this);
      assert !isDeleted();        // Race in user-land: load-after-delete
      return res;
    } catch( IOException ioe ) { throw Log.throwErr(ioe); }
  }
540186
protected void onSuperColumn(EntityMetadata m, boolean isRelation, List<String> relations, List<Object> entities,
        List<SuperColumn> superColumns, ByteBuffer key) {
        Object e = null;
        Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), key.array());

        ThriftRow tr = new ThriftRow(id, m.getTableName(), new ArrayList<Column>(0), superColumns,
            new ArrayList<CounterColumn>(0), new ArrayList<CounterSuperColumn>(0));

        e = getDataHandler().populateEntity(tr, m, KunderaCoreUtils.getEntity(e), relations, isRelation);
        if (log.isInfoEnabled()) {
            log.info("Populating data for super column family of clazz {} and row key {}.", m.getEntityClazz(),
                tr.getId());
        }

        if (e != null) {
            entities.add(e);
        }
    }
289287
@Override
    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
    {
        Connection conn = getConnection();
        try
        {
            // if entity is embeddable...call cql translator to get cql string!
            // use thrift client to execute cql query.

            if (isCql3Enabled(entityMetadata))
            {
                cqlClient.persist(entityMetadata, entity, conn.getClient(), rlHolders,
                        getTtlValues().get(entityMetadata.getTableName()));
            }
            else
            {
                Map<ByteBuffer, Map<String, List<Mutation>>> mutationMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>();
                prepareMutation(entityMetadata, entity, id, rlHolders, mutationMap);
                // Write Mutation map to database
                conn.getClient().batch_mutate(mutationMap, getConsistencyLevel());

                mutationMap.clear();
                mutationMap = null;
            }

        }
        catch (InvalidRequestException e)
        {
            log.error("Error while persisting record, Caused by: .", e);
            throw new KunderaException(e);
        }
        catch (TException e)
        {
            log.error("Error while persisting record, Caused by: .", e);
            throw new KunderaException(e);
        }
        catch (UnsupportedEncodingException e)
        {
            log.error("Error while persisting record, Caused by: .", e);
            throw new KunderaException(e);
        }
        finally
        {
            releaseConnection(conn);

            if (isTtlPerRequest())
            {
                getTtlValues().clear();
            }
        }
    }
114396
@Override
	public void cacheResult(
		List<CommerceAccountUserRel> commerceAccountUserRels) {
		for (CommerceAccountUserRel commerceAccountUserRel : commerceAccountUserRels) {
			if (entityCache.getResult(
						CommerceAccountUserRelModelImpl.ENTITY_CACHE_ENABLED,
						CommerceAccountUserRelImpl.class,
						commerceAccountUserRel.getPrimaryKey()) == null) {
				cacheResult(commerceAccountUserRel);
			}
			else {
				commerceAccountUserRel.resetOriginalValues();
			}
		}
	}
507817
@Override
    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
    {

        KuduSession session = kuduClient.newSession();
        KuduTable table = null;
        try
        {
            table = kuduClient.openTable(entityMetadata.getTableName());
        }
        catch (Exception e)
        {
            logger.error("Cannot open table : " + entityMetadata.getTableName(), e);
            throw new KunderaException("Cannot open table : " + entityMetadata.getTableName(), e);
        }
        Operation operation = isUpdate ? table.newUpdate() : table.newInsert();
        PartialRow row = operation.getRow();
        populatePartialRow(row, entityMetadata, entity);
        try
        {
            session.apply(operation);
        }
        catch (Exception e)
        {
            logger.error("Cannot insert/update row in table : " + entityMetadata.getTableName(), e);
            throw new KunderaException("Cannot insert/update row in table : " + entityMetadata.getTableName(), e);
        }
        finally
        {
            try
            {
                session.close();
            }
            catch (Exception e)
            {
                logger.error("Cannot close session", e);
                throw new KunderaException("Cannot close session", e);
            }
        }
    }
1273882
@Override
	public void cacheResult(
		List<CommerceNotificationTemplateUserSegmentRel> commerceNotificationTemplateUserSegmentRels) {
		for (CommerceNotificationTemplateUserSegmentRel commerceNotificationTemplateUserSegmentRel : commerceNotificationTemplateUserSegmentRels) {
			if (entityCache.getResult(
						CommerceNotificationTemplateUserSegmentRelModelImpl.ENTITY_CACHE_ENABLED,
						CommerceNotificationTemplateUserSegmentRelImpl.class,
						commerceNotificationTemplateUserSegmentRel.getPrimaryKey()) == null) {
				cacheResult(commerceNotificationTemplateUserSegmentRel);
			}
			else {
				commerceNotificationTemplateUserSegmentRel.resetOriginalValues();
			}
		}
	}
507614
@Override
    protected void onPersist(EntityMetadata metadata, Object entity, Object id, List<RelationHolder> relationHolders)
    {
        boolean proxyRemoved = removeKunderaProxies(metadata, entity, relationHolders);

        Transaction tx = null;

        s = getStatelessSession();
        tx = onBegin();
        try
        {
            if (!isUpdate)
            {
                id = s.insert(entity);

                // Update foreign Keys
                updateForeignKeys(metadata, id, relationHolders);
                onCommit(tx);/* tx.commit(); */
            }
            else
            {
                s.update(entity);

                if (proxyRemoved)
                {
                    updateForeignKeys(metadata, id, relationHolders);
                }

                onCommit(tx);
            }
        }
        // TODO: Bad code, get rid of these exceptions, currently necessary for
        // handling many to one case
        catch (org.hibernate.exception.ConstraintViolationException e)
        {
            s.update(entity);
            log.info(e.getMessage());
            onCommit(tx);
            // tx.commit();
        }
        catch (HibernateException e)
        {
            log.error("Error while persisting object of {}, Caused by {}.", metadata.getEntityClazz(), e);
            throw new PersistenceException(e);
        }
    }
830059
protected void initIndexPersistableListener() {
        _index.setPersistableListener(new PersistableListener() {
            @Override
            public void beforePersist() {
                try {
                    PersistableListener l = _listener;
                    if(l != null) l.beforePersist();
                } catch (Exception e) {
                    _logger.error("failed on calling beforePersist", e);
                }
                
                try {
                    _bytesDB.persist();
                } catch (Exception e) {
                    _logger.error("failed on calling beforePersist", e);
                }
            }
            
            @Override
            public void afterPersist() {
                try {
                    PersistableListener l = _listener;
                    if(l != null) l.afterPersist();
                } catch(Exception e) {
                    _logger.error("failed on calling afterPersist", e);
                }
            }
        });
    }
481382
@Override
	public void cacheResult(List<CommerceTaxFixedRate> commerceTaxFixedRates) {
		for (CommerceTaxFixedRate commerceTaxFixedRate : commerceTaxFixedRates) {
			if (entityCache.getResult(
						CommerceTaxFixedRateModelImpl.ENTITY_CACHE_ENABLED,
						CommerceTaxFixedRateImpl.class,
						commerceTaxFixedRate.getPrimaryKey()) == null) {
				cacheResult(commerceTaxFixedRate);
			}
			else {
				commerceTaxFixedRate.resetOriginalValues();
			}
		}
	}
755739
@Override
    protected List<Object> populateEntities(EntityMetadata m, Client client)
    {
        return onQuery(m, client);
    }
718129
@Override
    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
    {
        KunderaCoreUtils.printQuery(
                "Persist data into " + entityMetadata.getSchema() + "." + entityMetadata.getTableName() + " for " + id,
                showQuery);
        Row row = createRow(entityMetadata, entity, id, rlHolders);
        // TODO:: handle case for putDate??????

        tableAPI.put(row, null, null);
    }