use of org.datanucleus.state.AppIdObjectIdFieldConsumer in project datanucleus-rdbms by datanucleus.
the class PersistableMapping method setObjectAsValue.
/**
* Method to set an object reference (FK) in the datastore.
* @param ec The ExecutionContext
* @param ps The Prepared Statement
* @param param The parameter ids in the statement
* @param value The value to put in the statement at these ids
* @param ownerOP ObjectProvider for the owner object
* @param ownerFieldNumber Field number of this PC object in the owner
* @throws NotYetFlushedException Just put "null" in and throw "NotYetFlushedException", to be caught by ParameterSetter and will signal to the
* PC object being inserted that it needs to inform this object when it is inserted.
*/
private void setObjectAsValue(ExecutionContext ec, PreparedStatement ps, int[] param, Object value, ObjectProvider ownerOP, int ownerFieldNumber) {
Object id;
ApiAdapter api = ec.getApiAdapter();
if (!api.isPersistable(value)) {
throw new NucleusException(Localiser.msg("041016", value.getClass(), value)).setFatal();
}
ObjectProvider valueOP = ec.findObjectProvider(value);
try {
ClassLoaderResolver clr = ec.getClassLoaderResolver();
// Check if the field is attributed in the datastore
boolean hasDatastoreAttributedPrimaryKeyValues = hasDatastoreAttributedPrimaryKeyValues(ec.getMetaDataManager(), storeMgr, clr);
boolean inserted = false;
if (ownerFieldNumber >= 0) {
// Field mapping : is this field of the related object present in the datastore?
inserted = storeMgr.isObjectInserted(valueOP, ownerFieldNumber);
} else if (mmd == null) {
// Identity mapping : is the object inserted far enough to be considered of this mapping type?
inserted = storeMgr.isObjectInserted(valueOP, type);
}
if (valueOP != null) {
if (ec.getApiAdapter().isDetached(value) && valueOP.getReferencedPC() != null && ownerOP != null && mmd != null) {
// Still detached but started attaching so replace the field with what will be the attached
// Note that we have "fmd != null" here hence omitting any M-N relations where this is a join table
// mapping
ownerOP.replaceFieldMakeDirty(ownerFieldNumber, valueOP.getReferencedPC());
}
if (valueOP.isWaitingToBeFlushedToDatastore()) {
try {
// Related object is not yet flushed to the datastore so flush it so we can set the FK
valueOP.flush();
} catch (NotYetFlushedException nfe) {
// Could not flush it, maybe it has a relation to this object! so set as null TODO check nullability
if (ownerOP != null) {
ownerOP.updateFieldAfterInsert(value, ownerFieldNumber);
}
setObjectAsNull(ec, ps, param);
return;
}
}
} else {
if (ec.getApiAdapter().isDetached(value)) {
// Field value is detached and not yet started attaching, so attach
Object attachedValue = ec.persistObjectInternal(value, null, -1, ObjectProvider.PC);
if (attachedValue != value && ownerOP != null) {
// Replace the field value if using copy-on-attach
ownerOP.replaceFieldMakeDirty(ownerFieldNumber, attachedValue);
// Work from attached value now that it is attached
value = attachedValue;
}
valueOP = ec.findObjectProvider(value);
}
}
// 5) the value is the same object as we are inserting anyway and has its identity set
if (inserted || !ec.isInserting(value) || (!hasDatastoreAttributedPrimaryKeyValues && (this.mmd != null && this.mmd.isPrimaryKey())) || (!hasDatastoreAttributedPrimaryKeyValues && ownerOP == valueOP && api.getIdForObject(value) != null)) {
// The PC is either already inserted, or inserted down to the level we need, or not inserted at all,
// or the field is a PK and identity not attributed by the datastore
// Object either already exists, or is not yet being inserted.
id = api.getIdForObject(value);
// Check if the persistable object exists in this datastore
boolean requiresPersisting = false;
if (ec.getApiAdapter().isDetached(value) && ownerOP != null) {
// Detached object so needs attaching
if (ownerOP.isInserting()) {
// we can just return the value now and attach later (in InsertRequest)
if (!ec.getBooleanProperty(PropertyNames.PROPERTY_ATTACH_SAME_DATASTORE)) {
if (ec.getObjectFromCache(api.getIdForObject(value)) != null) {
// Object is in cache so exists for this datastore, so no point checking
} else {
try {
Object obj = ec.findObject(api.getIdForObject(value), true, false, value.getClass().getName());
if (obj != null) {
// Make sure this object is not retained in cache etc
ObjectProvider objOP = ec.findObjectProvider(obj);
if (objOP != null) {
ec.evictFromTransaction(objOP);
}
ec.removeObjectFromLevel1Cache(api.getIdForObject(value));
}
} catch (NucleusObjectNotFoundException onfe) {
// Object doesn't yet exist
requiresPersisting = true;
}
}
}
} else {
requiresPersisting = true;
}
} else if (id == null) {
// Transient object, so we need to persist it
requiresPersisting = true;
} else {
ExecutionContext pcEC = ec.getApiAdapter().getExecutionContext(value);
if (pcEC != null && ec != pcEC) {
throw new NucleusUserException(Localiser.msg("041015"), id);
}
}
if (requiresPersisting) {
// This PC object needs persisting (new or detached) to do the "set"
if (mmd != null && !mmd.isCascadePersist() && !ec.getApiAdapter().isDetached(value)) {
// Related PC object not persistent, but cant do cascade-persist so throw exception
if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
NucleusLogger.PERSISTENCE.debug(Localiser.msg("007006", mmd.getFullFieldName()));
}
throw new ReachableObjectNotCascadedException(mmd.getFullFieldName(), value);
}
if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
NucleusLogger.PERSISTENCE.debug(Localiser.msg("007007", mmd != null ? mmd.getFullFieldName() : null));
}
try {
Object pcNew = ec.persistObjectInternal(value, null, -1, ObjectProvider.PC);
if (hasDatastoreAttributedPrimaryKeyValues) {
ec.flushInternal(false);
}
id = api.getIdForObject(pcNew);
if (ec.getApiAdapter().isDetached(value) && ownerOP != null && mmd != null) {
// Update any detached reference to refer to the attached variant
ownerOP.replaceFieldMakeDirty(ownerFieldNumber, pcNew);
RelationType relationType = mmd.getRelationType(clr);
if (relationType == RelationType.MANY_TO_ONE_BI) {
// TODO Update the container to refer to the attached object
if (NucleusLogger.PERSISTENCE.isInfoEnabled()) {
NucleusLogger.PERSISTENCE.info("PCMapping.setObject : object " + ownerOP.getInternalObjectId() + " has field " + ownerFieldNumber + " that is 1-N bidirectional." + " Have just attached the N side so should really update the reference in the 1 side collection" + " to refer to this attached object. Not yet implemented");
}
} else if (relationType == RelationType.ONE_TO_ONE_BI) {
AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
// TODO Cater for more than 1 related field
ObjectProvider relatedOP = ec.findObjectProvider(pcNew);
relatedOP.replaceFieldMakeDirty(relatedMmds[0].getAbsoluteFieldNumber(), ownerOP.getObject());
}
}
} catch (NotYetFlushedException e) {
setObjectAsNull(ec, ps, param);
throw new NotYetFlushedException(value);
}
}
if (valueOP != null) {
valueOP.setStoringPC();
}
// If the field doesn't map to any datastore fields (e.g remote FK), omit the set process
if (getNumberOfDatastoreMappings() > 0) {
if (IdentityUtils.isDatastoreIdentity(id)) {
Object idKey = IdentityUtils.getTargetKeyForDatastoreIdentity(id);
try {
// Try as a Long
getDatastoreMapping(0).setObject(ps, param[0], idKey);
} catch (Exception e) {
// Must be a String
getDatastoreMapping(0).setObject(ps, param[0], idKey.toString());
}
} else {
boolean fieldsSet = false;
if (IdentityUtils.isSingleFieldIdentity(id) && javaTypeMappings.length > 1) {
Object key = IdentityUtils.getTargetKeyForSingleFieldIdentity(id);
AbstractClassMetaData keyCmd = ec.getMetaDataManager().getMetaDataForClass(key.getClass(), clr);
if (keyCmd != null && keyCmd.getIdentityType() == IdentityType.NONDURABLE) {
// Embedded ID - Make sure these are called starting at lowest first, in order
// We cannot just call OP.provideFields with all fields since that does last first
ObjectProvider keyOP = ec.findObjectProvider(key);
int[] fieldNums = keyCmd.getAllMemberPositions();
FieldManager fm = new AppIDObjectIdFieldManager(param, ec, ps, javaTypeMappings);
for (int i = 0; i < fieldNums.length; i++) {
keyOP.provideFields(new int[] { fieldNums[i] }, fm);
}
fieldsSet = true;
}
}
if (!fieldsSet) {
// Copy PK fields from identity to the object
FieldManager fm = new AppIDObjectIdFieldManager(param, ec, ps, javaTypeMappings);
api.copyKeyFieldsFromIdToObject(value, new AppIdObjectIdFieldConsumer(api, fm), id);
}
}
}
} else {
if (valueOP != null) {
valueOP.setStoringPC();
}
if (getNumberOfDatastoreMappings() > 0) {
// Object is in the process of being inserted so we cant use its id currently and we need to store
// a foreign key to it (which we cant yet do). Just put "null" in and throw "NotYetFlushedException",
// to be caught by ParameterSetter and will signal to the PC object being inserted that it needs
// to inform this object when it is inserted.
setObjectAsNull(ec, ps, param);
throw new NotYetFlushedException(value);
}
}
} finally {
if (valueOP != null) {
valueOP.unsetStoringPC();
}
}
}
use of org.datanucleus.state.AppIdObjectIdFieldConsumer in project datanucleus-rdbms by datanucleus.
the class AppIDObjectIdFieldManager method storeObjectField.
/**
* Method to store an object in a field.
* @param fieldNumber Number of the field
* @param value The value to use
*/
public void storeObjectField(int fieldNumber, Object value) {
ApiAdapter api = ec.getApiAdapter();
if (api.isPersistable(value)) {
api.copyKeyFieldsFromIdToObject(value, new AppIdObjectIdFieldConsumer(api, this), api.getIdForObject(value));
} else {
JavaTypeMapping mapping = javaTypeMappings[mappingNum++];
mapping.setObject(ec, statement, getParamsForField(mapping), value);
}
}
use of org.datanucleus.state.AppIdObjectIdFieldConsumer in project datanucleus-rdbms by datanucleus.
the class PersistableMapping method setObjectAsValue.
/**
* Method to set an object reference (FK) in the datastore.
* @param ec The ExecutionContext
* @param ps The Prepared Statement
* @param param The parameter ids in the statement
* @param value The value to put in the statement at these ids
* @param ownerSM StateManager for the owner object
* @param ownerFieldNumber Field number of this PC object in the owner
* @throws NotYetFlushedException Just put "null" in and throw "NotYetFlushedException", to be caught by ParameterSetter and will signal to the
* PC object being inserted that it needs to inform this object when it is inserted.
*/
private void setObjectAsValue(ExecutionContext ec, PreparedStatement ps, int[] param, Object value, DNStateManager ownerSM, int ownerFieldNumber) {
Object id;
ApiAdapter api = ec.getApiAdapter();
if (!api.isPersistable(value)) {
throw new NucleusException(Localiser.msg("041016", value.getClass(), value)).setFatal();
}
DNStateManager valueSM = ec.findStateManager(value);
try {
ClassLoaderResolver clr = ec.getClassLoaderResolver();
// Check if the field is attributed in the datastore
boolean hasDatastoreAttributedPrimaryKeyValues = hasDatastoreAttributedPrimaryKeyValues(ec.getMetaDataManager(), storeMgr, clr);
boolean inserted = false;
if (ownerFieldNumber >= 0) {
// Field mapping : is this field of the related object present in the datastore?
inserted = storeMgr.isObjectInserted(valueSM, ownerFieldNumber);
} else if (mmd == null) {
// Identity mapping : is the object inserted far enough to be considered of this mapping type?
inserted = storeMgr.isObjectInserted(valueSM, type);
}
if (valueSM != null) {
if (ec.getApiAdapter().isDetached(value) && valueSM.getReferencedPC() != null && ownerSM != null && mmd != null) {
// Still detached but started attaching so replace the field with what will be the attached
// Note that we have "fmd != null" here hence omitting any M-N relations where this is a join table
// mapping
ownerSM.replaceFieldMakeDirty(ownerFieldNumber, valueSM.getReferencedPC());
}
if (valueSM.isWaitingToBeFlushedToDatastore()) {
try {
// Related object is not yet flushed to the datastore so flush it so we can set the FK
valueSM.flush();
} catch (NotYetFlushedException nfe) {
// Could not flush it, maybe it has a relation to this object! so set as null TODO check nullability
if (ownerSM != null) {
ownerSM.updateFieldAfterInsert(value, ownerFieldNumber);
}
setObjectAsNull(ec, ps, param);
return;
}
}
} else {
if (ec.getApiAdapter().isDetached(value)) {
// Field value is detached and not yet started attaching, so attach
Object attachedValue = ec.persistObjectInternal(value, null, -1, PersistableObjectType.PC);
if (attachedValue != value && ownerSM != null) {
// Replace the field value if using copy-on-attach
ownerSM.replaceFieldMakeDirty(ownerFieldNumber, attachedValue);
// Work from attached value now that it is attached
value = attachedValue;
}
valueSM = ec.findStateManager(value);
}
}
// 5) the value is the same object as we are inserting anyway and has its identity set
if (inserted || !ec.isInserting(value) || (!hasDatastoreAttributedPrimaryKeyValues && (this.mmd != null && this.mmd.isPrimaryKey())) || (!hasDatastoreAttributedPrimaryKeyValues && ownerSM == valueSM && api.getIdForObject(value) != null)) {
// The PC is either already inserted, or inserted down to the level we need, or not inserted at all,
// or the field is a PK and identity not attributed by the datastore
// Object either already exists, or is not yet being inserted.
id = api.getIdForObject(value);
// Check if the persistable object exists in this datastore
boolean requiresPersisting = false;
if (ec.getApiAdapter().isDetached(value) && ownerSM != null) {
// Detached object so needs attaching
if (ownerSM.isInserting()) {
// we can just return the value now and attach later (in InsertRequest)
if (!ec.getBooleanProperty(PropertyNames.PROPERTY_ATTACH_SAME_DATASTORE)) {
if (ec.getObjectFromCache(api.getIdForObject(value)) != null) {
// Object is in cache so exists for this datastore, so no point checking
} else {
try {
Object obj = ec.findObject(api.getIdForObject(value), true, false, value.getClass().getName());
if (obj != null) {
// Make sure this object is not retained in cache etc
DNStateManager sm = ec.findStateManager(obj);
if (sm != null) {
ec.evictFromTransaction(sm);
}
ec.removeObjectFromLevel1Cache(api.getIdForObject(value));
}
} catch (NucleusObjectNotFoundException onfe) {
// Object doesn't yet exist
requiresPersisting = true;
}
}
}
} else {
requiresPersisting = true;
}
} else if (id == null) {
// Transient object, so we need to persist it
requiresPersisting = true;
} else {
ExecutionContext pcEC = ec.getApiAdapter().getExecutionContext(value);
if (pcEC != null && ec != pcEC) {
throw new NucleusUserException(Localiser.msg("041015"), id);
}
}
if (requiresPersisting) {
// This PC object needs persisting (new or detached) to do the "set"
if (mmd != null && !mmd.isCascadePersist() && !ec.getApiAdapter().isDetached(value)) {
// Related PC object not persistent, but cant do cascade-persist so throw exception
if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
NucleusLogger.PERSISTENCE.debug(Localiser.msg("007006", mmd.getFullFieldName()));
}
throw new ReachableObjectNotCascadedException(mmd.getFullFieldName(), value);
}
if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
NucleusLogger.PERSISTENCE.debug(Localiser.msg("007007", ownerSM != null ? IdentityUtils.getPersistableIdentityForId(ownerSM.getInternalObjectId()) : id, mmd != null ? mmd.getFullFieldName() : null));
}
try {
Object pcNew = ec.persistObjectInternal(value, null, -1, PersistableObjectType.PC);
if (hasDatastoreAttributedPrimaryKeyValues) {
ec.flushInternal(false);
}
id = api.getIdForObject(pcNew);
if (ec.getApiAdapter().isDetached(value) && ownerSM != null && mmd != null) {
// Update any detached reference to refer to the attached variant
ownerSM.replaceFieldMakeDirty(ownerFieldNumber, pcNew);
RelationType relationType = mmd.getRelationType(clr);
if (relationType == RelationType.MANY_TO_ONE_BI) {
// TODO Update the container to refer to the attached object
if (NucleusLogger.PERSISTENCE.isInfoEnabled()) {
NucleusLogger.PERSISTENCE.info("PCMapping.setObject : object " + ownerSM.getInternalObjectId() + " has field " + ownerFieldNumber + " that is 1-N bidirectional." + " Have just attached the N side so should really update the reference in the 1 side collection" + " to refer to this attached object. Not yet implemented");
}
} else if (relationType == RelationType.ONE_TO_ONE_BI) {
AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
// TODO Cater for more than 1 related field
DNStateManager relatedSM = ec.findStateManager(pcNew);
relatedSM.replaceFieldMakeDirty(relatedMmds[0].getAbsoluteFieldNumber(), ownerSM.getObject());
}
}
} catch (NotYetFlushedException e) {
setObjectAsNull(ec, ps, param);
throw new NotYetFlushedException(value);
}
}
if (valueSM != null) {
valueSM.setStoringPC();
}
// If the field doesn't map to any columns (e.g remote FK), omit the set process
if (getNumberOfColumnMappings() > 0) {
if (IdentityUtils.isDatastoreIdentity(id)) {
Object idKey = IdentityUtils.getTargetKeyForDatastoreIdentity(id);
try {
// Try as a Long
getColumnMapping(0).setObject(ps, param[0], idKey);
} catch (Exception e) {
// Must be a String
getColumnMapping(0).setObject(ps, param[0], idKey.toString());
}
} else {
boolean fieldsSet = false;
if (IdentityUtils.isSingleFieldIdentity(id) && javaTypeMappings.length > 1) {
Object key = IdentityUtils.getTargetKeyForSingleFieldIdentity(id);
AbstractClassMetaData keyCmd = ec.getMetaDataManager().getMetaDataForClass(key.getClass(), clr);
if (keyCmd != null && keyCmd.getIdentityType() == IdentityType.NONDURABLE) {
// Embedded ID - Make sure these are called starting at lowest first, in order
// We cannot just call SM.provideFields with all fields since that does last first
DNStateManager keySM = ec.findStateManager(key);
int[] fieldNums = keyCmd.getAllMemberPositions();
FieldManager fm = new AppIDObjectIdFieldManager(param, ec, ps, javaTypeMappings);
for (int i = 0; i < fieldNums.length; i++) {
keySM.provideFields(new int[] { fieldNums[i] }, fm);
}
fieldsSet = true;
}
}
if (!fieldsSet) {
// Copy PK fields from identity to the object
FieldManager fm = new AppIDObjectIdFieldManager(param, ec, ps, javaTypeMappings);
api.copyKeyFieldsFromIdToObject(value, new AppIdObjectIdFieldConsumer(api, fm), id);
}
}
}
} else {
if (valueSM != null) {
valueSM.setStoringPC();
}
if (getNumberOfColumnMappings() > 0) {
// Object is in the process of being inserted so we cant use its id currently and we need to store
// a foreign key to it (which we cant yet do). Just put "null" in and throw "NotYetFlushedException",
// to be caught by ParameterSetter and will signal to the PC object being inserted that it needs
// to inform this object when it is inserted.
setObjectAsNull(ec, ps, param);
throw new NotYetFlushedException(value);
}
}
} finally {
if (valueSM != null) {
valueSM.unsetStoringPC();
}
}
}
Aggregations