if (value == null) {
throw new GenericEntityException("Cannot create a null value");
}
GenericHelper helper = getEntityHelper(value.getEntityName());
// just make sure it is this delegator...
value.setDelegator(this);
// this will throw an IllegalArgumentException if the entity for the value does not have one pk field, or if it already has a value set for the one pk field
value.setNextSeqId();
boolean beganTransaction = false;
try {
if (alwaysUseTransaction) {
beganTransaction = TransactionUtil.begin();
}
EntityEcaRuleRunner<?> ecaRunner = this.getEcaRuleRunner(value.getEntityName());
ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_CREATE, value, false);
ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_CREATE, value, false);
value.setDelegator(this);
this.encryptFields(value);
// if audit log on for any fields, save new value with no old value because it's a create
if (value != null && value.getModelEntity().getHasFieldWithAuditLog()) {
createEntityAuditLogAll(value, false, false);
}
try {
value = helper.create(value);
if (testMode) {
storeForTestRollback(new TestOperation(OperationType.INSERT, value));
}
} catch (GenericEntityException e) {
// see if this was caused by an existing record before resetting the sequencer and trying again
// NOTE: use the helper directly so ECA rules, etc won't be run
GenericValue existingValue = null;
try {
existingValue = helper.findByPrimaryKey(value.getPrimaryKey());
} catch (GenericEntityException e1) {
// ignore this error, if not found it'll probably be a GenericEntityNotFoundException
// it is important to not let this get thrown because it will mask the original exception
}
if (existingValue == null) {
throw e;
} else {
Debug.logInfo("Error creating entity record with a sequenced value [" + value.getPrimaryKey() + "], trying again about to refresh bank for entity [" + value.getEntityName() + "]", module);
// found an existing value... was probably a duplicate key, so clean things up and try again
this.sequencer.forceBankRefresh(value.getEntityName(), 1);
value.setNextSeqId();
value = helper.create(value);
Debug.logInfo("Successfully created new entity record on retry with a sequenced value [" + value.getPrimaryKey() + "], after getting refreshed bank for entity [" + value.getEntityName() + "]", module);
if (testMode) {
storeForTestRollback(new TestOperation(OperationType.INSERT, value));
}