Search in sources :

Example 6 with NucleusObjectNotFoundException

use of org.datanucleus.exceptions.NucleusObjectNotFoundException in project datanucleus-rdbms by datanucleus.

the class OracleBlobColumnMapping method setPostProcessing.

@SuppressWarnings("deprecation")
@Override
public void setPostProcessing(DNStateManager sm, Object value) {
    // Oracle requires that a BLOB is initialised with EMPTY_BLOB() and then you retrieve the column and update its BLOB value. Performs a statement
    // SELECT {blobColumn} FROM TABLE WHERE ID=? FOR UPDATE
    // and then updates the Blob value returned.
    ExecutionContext ec = sm.getExecutionContext();
    byte[] bytes = (byte[]) value;
    Table table = column.getTable();
    RDBMSStoreManager storeMgr = table.getStoreManager();
    if (table instanceof DatastoreClass) {
        // BLOB within a primary table
        DatastoreClass classTable = (DatastoreClass) table;
        // Generate "SELECT {blobColumn} FROM TABLE WHERE ID=? FOR UPDATE" statement
        SelectStatement sqlStmt = new SelectStatement(storeMgr, table, null, null);
        sqlStmt.setClassLoaderResolver(ec.getClassLoaderResolver());
        sqlStmt.addExtension(SQLStatement.EXTENSION_LOCK_FOR_UPDATE, true);
        SQLTable blobSqlTbl = SQLStatementHelper.getSQLTableForMappingOfTable(sqlStmt, sqlStmt.getPrimaryTable(), mapping);
        sqlStmt.select(blobSqlTbl, column, null);
        StatementClassMapping mappingDefinition = new StatementClassMapping();
        AbstractClassMetaData cmd = sm.getClassMetaData();
        SQLExpressionFactory exprFactory = storeMgr.getSQLExpressionFactory();
        int inputParamNum = 1;
        if (cmd.getIdentityType() == IdentityType.DATASTORE) {
            // Datastore identity value for input
            JavaTypeMapping datastoreIdMapping = classTable.getSurrogateMapping(SurrogateColumnType.DATASTORE_ID, false);
            SQLExpression expr = exprFactory.newExpression(sqlStmt, sqlStmt.getPrimaryTable(), datastoreIdMapping);
            SQLExpression val = exprFactory.newLiteralParameter(sqlStmt, datastoreIdMapping, null, "ID");
            sqlStmt.whereAnd(expr.eq(val), true);
            StatementMappingIndex datastoreIdx = mappingDefinition.getMappingForMemberPosition(SurrogateColumnType.DATASTORE_ID.getFieldNumber());
            if (datastoreIdx == null) {
                datastoreIdx = new StatementMappingIndex(datastoreIdMapping);
                mappingDefinition.addMappingForMember(SurrogateColumnType.DATASTORE_ID.getFieldNumber(), datastoreIdx);
            }
            datastoreIdx.addParameterOccurrence(new int[] { inputParamNum });
        } else if (cmd.getIdentityType() == IdentityType.APPLICATION) {
            // Application identity value(s) for input
            int[] pkNums = cmd.getPKMemberPositions();
            for (int i = 0; i < pkNums.length; i++) {
                AbstractMemberMetaData mmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(pkNums[i]);
                JavaTypeMapping pkMapping = classTable.getMemberMapping(mmd);
                SQLExpression expr = exprFactory.newExpression(sqlStmt, sqlStmt.getPrimaryTable(), pkMapping);
                SQLExpression val = exprFactory.newLiteralParameter(sqlStmt, pkMapping, null, "PK" + i);
                sqlStmt.whereAnd(expr.eq(val), true);
                StatementMappingIndex pkIdx = mappingDefinition.getMappingForMemberPosition(pkNums[i]);
                if (pkIdx == null) {
                    pkIdx = new StatementMappingIndex(pkMapping);
                    mappingDefinition.addMappingForMember(pkNums[i], pkIdx);
                }
                int[] inputParams = new int[pkMapping.getNumberOfColumnMappings()];
                for (int j = 0; j < pkMapping.getNumberOfColumnMappings(); j++) {
                    inputParams[j] = inputParamNum++;
                }
                pkIdx.addParameterOccurrence(inputParams);
            }
        }
        String textStmt = sqlStmt.getSQLText().toSQL();
        if (sm.isEmbedded()) {
            // This mapping is embedded, so navigate back to the real owner since that is the "id" in the table
            DNStateManager embeddedOwner = ec.getOwnerForEmbeddedStateManager(sm);
            if (embeddedOwner != null) {
                // TODO Should check if the owner is stored in this table
                sm = embeddedOwner;
            }
        }
        try {
            ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
            SQLController sqlControl = storeMgr.getSQLController();
            try {
                PreparedStatement ps = sqlControl.getStatementForQuery(mconn, textStmt);
                try {
                    // Provide the primary key field(s) to the JDBC statement
                    if (cmd.getIdentityType() == IdentityType.DATASTORE) {
                        StatementMappingIndex datastoreIdx = mappingDefinition.getMappingForMemberPosition(SurrogateColumnType.DATASTORE_ID.getFieldNumber());
                        for (int i = 0; i < datastoreIdx.getNumberOfParameterOccurrences(); i++) {
                            classTable.getSurrogateMapping(SurrogateColumnType.DATASTORE_ID, false).setObject(ec, ps, datastoreIdx.getParameterPositionsForOccurrence(i), sm.getInternalObjectId());
                        }
                    } else if (cmd.getIdentityType() == IdentityType.APPLICATION) {
                        sm.provideFields(cmd.getPKMemberPositions(), new ParameterSetter(sm, ps, mappingDefinition));
                    }
                    ResultSet rs = sqlControl.executeStatementQuery(ec, mconn, textStmt, ps);
                    try {
                        if (!rs.next()) {
                            throw new NucleusObjectNotFoundException(Localiser.msg("050018", IdentityUtils.getPersistableIdentityForId(sm.getInternalObjectId())));
                        }
                        DatastoreAdapter dba = storeMgr.getDatastoreAdapter();
                        int jdbcMajorVersion = dba.getDriverMajorVersion();
                        if (dba.getDatastoreDriverName().equalsIgnoreCase(OracleAdapter.OJDBC_DRIVER_NAME) && jdbcMajorVersion < 10) {
                            oracle.sql.BLOB blob = null;
                            if (jdbcMajorVersion <= 8) {
                                // Oracle JDBC <= v8
                                // We are effectively doing the following line but don't want to impose having Oracle <= v10 in the CLASSPATH, just any Oracle driver
                                // blob = ((oracle.jdbc.driver.OracleResultSet)rs).getBLOB(1);
                                Method getBlobMethod = ClassUtils.getMethodForClass(rs.getClass(), "getBLOB", new Class[] { int.class });
                                try {
                                    blob = (BLOB) getBlobMethod.invoke(rs, new Object[] { 1 });
                                } catch (Throwable thr) {
                                    throw new NucleusDataStoreException("Error in getting BLOB", thr);
                                }
                            } else {
                                // Oracle JDBC v9
                                blob = (BLOB) rs.getBlob(1);
                            }
                            if (blob != null) {
                                // Deprecated but what can you do
                                blob.putBytes(1, bytes);
                            }
                        } else {
                            // Oracle JDBC v10+ supposedly use the JDBC standard class for Blobs
                            java.sql.Blob blob = rs.getBlob(1);
                            if (blob != null) {
                                blob.setBytes(1, bytes);
                            }
                        }
                    } finally {
                        rs.close();
                    }
                } finally {
                    sqlControl.closeStatement(mconn, ps);
                }
            } finally {
                mconn.release();
            }
        } catch (SQLException e) {
            throw new NucleusDataStoreException("Update of BLOB value failed: " + textStmt, e);
        }
    } else {
        // TODO Support join table
        throw new NucleusDataStoreException("We do not support INSERT/UPDATE BLOB post processing of non-primary table " + table);
    }
}
Also used : SQLExpressionFactory(org.datanucleus.store.rdbms.sql.expression.SQLExpressionFactory) SQLExpression(org.datanucleus.store.rdbms.sql.expression.SQLExpression) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) SQLException(java.sql.SQLException) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) ParameterSetter(org.datanucleus.store.rdbms.fieldmanager.ParameterSetter) NucleusObjectNotFoundException(org.datanucleus.exceptions.NucleusObjectNotFoundException) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) SQLController(org.datanucleus.store.rdbms.SQLController) SelectStatement(org.datanucleus.store.rdbms.sql.SelectStatement) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) SQLTable(org.datanucleus.store.rdbms.sql.SQLTable) BLOB(oracle.sql.BLOB) ResultSet(java.sql.ResultSet) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) SQLTable(org.datanucleus.store.rdbms.sql.SQLTable) Table(org.datanucleus.store.rdbms.table.Table) PreparedStatement(java.sql.PreparedStatement) Method(java.lang.reflect.Method) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager) StatementClassMapping(org.datanucleus.store.rdbms.query.StatementClassMapping) ExecutionContext(org.datanucleus.ExecutionContext) DatastoreAdapter(org.datanucleus.store.rdbms.adapter.DatastoreAdapter) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) DNStateManager(org.datanucleus.state.DNStateManager) Blob(java.sql.Blob) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData)

Example 7 with NucleusObjectNotFoundException

use of org.datanucleus.exceptions.NucleusObjectNotFoundException in project datanucleus-rdbms by datanucleus.

the class MultiPersistableMapping method getObject.

/**
 * Method to retrieve an object of this type from the ResultSet.
 * @param ec execution context
 * @param rs The ResultSet
 * @param pos The parameter positions
 * @return The object
 */
public Object getObject(ExecutionContext ec, final ResultSet rs, int[] pos) {
    // Go through the possible types for this field and find a non-null value (if there is one)
    int n = 0;
    for (int i = 0; i < javaTypeMappings.length; i++) {
        int[] posMapping;
        if (n >= pos.length) {
            // this means we store all implementations to the same columns, so we reset the index
            n = 0;
        }
        if (javaTypeMappings[i].getReferenceMapping() != null) {
            posMapping = new int[javaTypeMappings[i].getReferenceMapping().getNumberOfColumnMappings()];
        } else {
            posMapping = new int[javaTypeMappings[i].getNumberOfColumnMappings()];
        }
        for (int j = 0; j < posMapping.length; j++) {
            posMapping[j] = pos[n++];
        }
        Object value = null;
        try {
            // Retrieve the value (PC object) for this mappings' object
            value = javaTypeMappings[i].getObject(ec, rs, posMapping);
            if (value != null) {
                if (IdentityUtils.isDatastoreIdentity(value)) {
                    // What situation is this catering for exactly ?
                    Column col = null;
                    if (javaTypeMappings[i].getReferenceMapping() != null) {
                        col = javaTypeMappings[i].getReferenceMapping().getColumnMapping(0).getColumn();
                    } else {
                        col = javaTypeMappings[i].getColumnMapping(0).getColumn();
                    }
                    String className = col.getStoredJavaType();
                    value = ec.getNucleusContext().getIdentityManager().getDatastoreId(className, IdentityUtils.getTargetKeyForDatastoreIdentity(value));
                    return ec.findObject(value, false, true, null);
                } else if (ec.getClassLoaderResolver().classForName(getType()).isAssignableFrom(value.getClass())) {
                    return value;
                }
            }
        } catch (NullValueException e) {
        // expected if implementation object is null and has primitive fields in the primary key
        } catch (NucleusObjectNotFoundException onfe) {
        // expected, will try next implementation
        }
    }
    return null;
}
Also used : Column(org.datanucleus.store.rdbms.table.Column) NucleusObjectNotFoundException(org.datanucleus.exceptions.NucleusObjectNotFoundException) NullValueException(org.datanucleus.store.rdbms.exceptions.NullValueException)

Example 8 with NucleusObjectNotFoundException

use of org.datanucleus.exceptions.NucleusObjectNotFoundException in project datanucleus-rdbms by datanucleus.

the class PersistableMapping method preDelete.

/**
 * Method executed just before the owning object is deleted, allowing tidying up of any relation information.
 * @param sm StateManager for the owner
 */
public void preDelete(DNStateManager sm) {
    int fieldNumber = mmd.getAbsoluteFieldNumber();
    ExecutionContext ec = sm.getExecutionContext();
    ClassLoaderResolver clr = ec.getClassLoaderResolver();
    RelationType relationType = mmd.getRelationType(clr);
    AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
    // Check if we should delete the related object when this object is deleted
    boolean dependent = mmd.isDependent();
    if (mmd.isCascadeRemoveOrphans()) {
        // JPA allows "orphan removal" to define deletion of the other side
        dependent = true;
    }
    if (!dependent) {
        if (relationType == RelationType.ONE_TO_ONE_UNI) {
            // Special case of FK this side and unidirectional, just return
            return;
        }
    // TODO If we have the FK and not dependent then should avoid the load on the related object
    }
    if (!sm.isFieldLoaded(fieldNumber)) {
        // Load the field if we need its value
        try {
            // First try from stored FK value, otherwise load from database
            if (!sm.loadStoredField(fieldNumber)) {
                sm.loadField(fieldNumber);
            }
        } catch (NucleusObjectNotFoundException onfe) {
            // Already deleted so just return
            return;
        }
    }
    Object pc = sm.provideField(fieldNumber);
    pc = mmd.isSingleCollection() ? SCOUtils.singleCollectionValue(getStoreManager().getNucleusContext().getTypeManager(), pc) : pc;
    if (pc == null) {
        // Null value so nothing to do
        return;
    }
    // N-1 Uni, so delete join table entry
    if (relationType == RelationType.MANY_TO_ONE_UNI) {
        // Update join table entry
        PersistableRelationStore store = (PersistableRelationStore) storeMgr.getBackingStoreForField(clr, mmd, mmd.getType());
        store.remove(sm);
    }
    // Check if the field has a FK defined TODO Cater for more than 1 related field
    boolean hasFK = false;
    if (!dependent) {
        // Not dependent, so check if the datastore has a FK and will take care of it for us
        if (mmd.getForeignKeyMetaData() != null) {
            hasFK = true;
        }
        if (RelationType.isBidirectional(relationType) && relatedMmds[0].getForeignKeyMetaData() != null) {
            hasFK = true;
        }
        if (ec.getStringProperty(PropertyNames.PROPERTY_DELETION_POLICY).equals("JDO2")) {
            // JDO doesn't currently take note of foreign-key
            hasFK = false;
        }
    }
    // There may be some corner cases that this code doesn't yet cater for
    if (relationType == RelationType.ONE_TO_ONE_UNI || (relationType == RelationType.ONE_TO_ONE_BI && mmd.getMappedBy() == null)) {
        // 1-1 with FK at this side (owner of the relation)
        if (dependent) {
            boolean relatedObjectDeleted = ec.getApiAdapter().isDeleted(pc);
            if (isNullable() && !relatedObjectDeleted) {
                // Other object not yet deleted, but the field is nullable so just null out the FK
                // TODO Not doing this would cause errors in 1-1 uni relations (e.g AttachDetachTest)
                // TODO Log this since it affects the resultant objects
                sm.replaceFieldMakeDirty(fieldNumber, null);
                storeMgr.getPersistenceHandler().updateObject(sm, new int[] { fieldNumber });
                if (!relatedObjectDeleted) {
                    // Mark the other object for deletion since not yet tagged
                    ec.deleteObjectInternal(pc);
                }
            } else {
                // Can't just delete the other object since that would cause a FK constraint violation. Do nothing - handled by DeleteRequest on other object
                if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
                    NucleusLogger.DATASTORE_PERSIST.debug(Localiser.msg("041017", StringUtils.toJVMIDString(sm.getObject()), mmd.getFullFieldName()));
                }
            }
        } else {
            // We're deleting the FK at this side so shouldn't be an issue
            AbstractMemberMetaData relatedMmd = mmd.getRelatedMemberMetaDataForObject(clr, sm.getObject(), pc);
            if (relatedMmd != null) {
                DNStateManager otherSM = ec.findStateManager(pc);
                if (otherSM != null) {
                    // Managed Relations : 1-1 bidir, so null out the object at the other
                    Object currentValue = otherSM.provideField(relatedMmd.getAbsoluteFieldNumber());
                    if (currentValue != null) {
                        if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
                            NucleusLogger.PERSISTENCE.debug(Localiser.msg("041019", StringUtils.toJVMIDString(pc), relatedMmd.getFullFieldName(), sm.getObjectAsPrintable()));
                        }
                        otherSM.replaceFieldMakeDirty(relatedMmd.getAbsoluteFieldNumber(), null);
                        if (ec.getManageRelations()) {
                            otherSM.getExecutionContext().getRelationshipManager(otherSM).relationChange(relatedMmd.getAbsoluteFieldNumber(), sm.getObject(), null);
                        }
                    }
                }
            }
        }
    } else if (relationType == RelationType.ONE_TO_ONE_BI && mmd.getMappedBy() != null) {
        // 1-1 with FK at other side
        DatastoreClass relatedTable = storeMgr.getDatastoreClass(relatedMmds[0].getClassName(), clr);
        JavaTypeMapping relatedMapping = relatedTable.getMemberMapping(relatedMmds[0]);
        boolean isNullable = relatedMapping.isNullable();
        DNStateManager otherSM = ec.findStateManager(pc);
        if (dependent) {
            if (isNullable) {
                // Null out the FK in the datastore using a direct update (since we are deleting)
                otherSM.replaceFieldMakeDirty(relatedMmds[0].getAbsoluteFieldNumber(), null);
                storeMgr.getPersistenceHandler().updateObject(otherSM, new int[] { relatedMmds[0].getAbsoluteFieldNumber() });
            }
            // Mark the other object for deletion
            ec.deleteObjectInternal(pc);
        } else if (!hasFK) {
            if (isNullable()) {
                Object currentRelatedValue = otherSM.provideField(relatedMmds[0].getAbsoluteFieldNumber());
                if (currentRelatedValue != null) {
                    // Null out the FK in the datastore using a direct update (since we are deleting)
                    otherSM.replaceFieldMakeDirty(relatedMmds[0].getAbsoluteFieldNumber(), null);
                    storeMgr.getPersistenceHandler().updateObject(otherSM, new int[] { relatedMmds[0].getAbsoluteFieldNumber() });
                    // Managed Relations : 1-1 bidir, so null out the object at the other
                    if (ec.getManageRelations()) {
                        otherSM.getExecutionContext().getRelationshipManager(otherSM).relationChange(relatedMmds[0].getAbsoluteFieldNumber(), sm.getObject(), null);
                    }
                }
            } else {
            // TODO Remove it
            }
        } else {
        // User has a FK defined (in MetaData) so let the datastore take care of it
        }
    } else if (relationType == RelationType.MANY_TO_ONE_BI) {
        DNStateManager otherSM = ec.findStateManager(pc);
        if (relatedMmds[0].getJoinMetaData() == null) {
            // N-1 with FK at this side
            if (otherSM.isDeleting()) {
            // Other object is being deleted too but this side has the FK so just delete this object
            } else {
                // Other object is not being deleted so delete it if necessary
                if (dependent) {
                    if (isNullable()) {
                        // TODO Datastore nullability info can be unreliable so try to avoid this call
                        // Null out the FK in the datastore using a direct update (since we are deleting)
                        sm.replaceFieldMakeDirty(fieldNumber, null);
                        storeMgr.getPersistenceHandler().updateObject(sm, new int[] { fieldNumber });
                    }
                    if (ec.getApiAdapter().isDeleted(pc)) {
                    // Object is already tagged for deletion but we're deleting the FK so leave til flush()
                    } else {
                        // Mark the other object for deletion
                        ec.deleteObjectInternal(pc);
                    }
                } else {
                    // Managed Relations : remove element from collection/map
                    if (relatedMmds[0].hasCollection()) {
                        // Only update the other side if not already being deleted
                        if (!ec.getApiAdapter().isDeleted(otherSM.getObject()) && !otherSM.isDeleting()) {
                            // Make sure the other object is updated in any caches
                            ec.markDirty(otherSM, false);
                            // Make sure collection field is loaded
                            otherSM.isLoaded(relatedMmds[0].getAbsoluteFieldNumber());
                            Collection otherColl = (Collection) otherSM.provideField(relatedMmds[0].getAbsoluteFieldNumber());
                            if (otherColl != null) {
                                if (ec.getManageRelations()) {
                                    otherSM.getExecutionContext().getRelationshipManager(otherSM).relationRemove(relatedMmds[0].getAbsoluteFieldNumber(), sm.getObject());
                                }
                                if (otherColl.contains(sm.getObject())) {
                                    // TODO Localise this message
                                    NucleusLogger.PERSISTENCE.debug("ManagedRelationships : delete of object causes removal from collection at " + relatedMmds[0].getFullFieldName());
                                    otherColl.remove(sm.getObject());
                                }
                            }
                        }
                    } else if (relatedMmds[0].hasMap()) {
                    // TODO Cater for maps, but what is the key/value pair ?
                    }
                }
            }
        } else {
            // N-1 with join table so no FK here so need to remove from Collection/Map first? (managed relations)
            if (dependent) {
                // Mark the other object for deletion
                ec.deleteObjectInternal(pc);
            } else {
                // Managed Relations : remove element from collection/map
                if (relatedMmds[0].hasCollection()) {
                    // Only update the other side if not already being deleted
                    if (!ec.getApiAdapter().isDeleted(otherSM.getObject()) && !otherSM.isDeleting()) {
                        // Make sure the other object is updated in any caches
                        ec.markDirty(otherSM, false);
                        // Make sure the other object has the collection loaded so does this change
                        otherSM.isLoaded(relatedMmds[0].getAbsoluteFieldNumber());
                        Collection otherColl = (Collection) otherSM.provideField(relatedMmds[0].getAbsoluteFieldNumber());
                        if (otherColl != null && otherColl.contains(sm.getObject())) {
                            // TODO Localise this
                            NucleusLogger.PERSISTENCE.debug("ManagedRelationships : delete of object causes removal from collection at " + relatedMmds[0].getFullFieldName());
                            otherColl.remove(sm.getObject());
                        }
                    }
                } else if (relatedMmds[0].hasMap()) {
                // TODO Cater for maps, but what is the key/value pair ?
                }
            }
        }
    } else if (relationType == RelationType.MANY_TO_ONE_UNI) {
        // N-1 uni with join table
        if (dependent) {
            // Mark the other object for deletion
            ec.deleteObjectInternal(pc);
        }
    } else {
    // No relation so what is this field ?
    }
}
Also used : ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) NucleusObjectNotFoundException(org.datanucleus.exceptions.NucleusObjectNotFoundException) ExecutionContext(org.datanucleus.ExecutionContext) RelationType(org.datanucleus.metadata.RelationType) Collection(java.util.Collection) SCOCollection(org.datanucleus.store.types.SCOCollection) DNStateManager(org.datanucleus.state.DNStateManager) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) PersistableRelationStore(org.datanucleus.store.types.scostore.PersistableRelationStore)

Example 9 with NucleusObjectNotFoundException

use of org.datanucleus.exceptions.NucleusObjectNotFoundException in project datanucleus-rdbms by datanucleus.

the class LocateBulkRequest method execute.

/**
 * Method performing the location of the records in the datastore.
 * @param sms StateManagers to be located
 * @throws NucleusObjectNotFoundException with nested exceptions for each of missing objects (if any)
 */
public void execute(DNStateManager[] sms) {
    if (sms == null || sms.length == 0) {
        return;
    }
    if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
        // Debug information about what we are retrieving
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < sms.length; i++) {
            if (i > 0) {
                str.append(", ");
            }
            str.append(sms[i].getInternalObjectId());
        }
        NucleusLogger.PERSISTENCE.debug(Localiser.msg("052223", str.toString(), table));
    }
    ExecutionContext ec = sms[0].getExecutionContext();
    RDBMSStoreManager storeMgr = table.getStoreManager();
    AbstractClassMetaData cmd = sms[0].getClassMetaData();
    // Override with pessimistic lock where specified
    LockMode lockType = ec.getLockManager().getLockMode(sms[0].getInternalObjectId());
    boolean locked = (lockType == LockMode.LOCK_PESSIMISTIC_READ || lockType == LockMode.LOCK_PESSIMISTIC_WRITE) ? true : ec.getSerializeReadForClass(cmd.getFullClassName());
    String statement = getStatement(table, sms, locked);
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            PreparedStatement ps = sqlControl.getStatementForQuery(mconn, statement);
            try {
                // Provide the primary key field(s)
                for (int i = 0; i < sms.length; i++) {
                    if (cmd.getIdentityType() == IdentityType.DATASTORE) {
                        StatementMappingIndex datastoreIdx = mappingDefinitions[i].getMappingForMemberPosition(SurrogateColumnType.DATASTORE_ID.getFieldNumber());
                        for (int j = 0; j < datastoreIdx.getNumberOfParameterOccurrences(); j++) {
                            table.getSurrogateMapping(SurrogateColumnType.DATASTORE_ID, false).setObject(ec, ps, datastoreIdx.getParameterPositionsForOccurrence(j), sms[i].getInternalObjectId());
                        }
                    } else if (cmd.getIdentityType() == IdentityType.APPLICATION) {
                        sms[i].provideFields(cmd.getPKMemberPositions(), new ParameterSetter(sms[i], ps, mappingDefinitions[i]));
                    }
                }
                // Execute the statement
                ResultSet rs = sqlControl.executeStatementQuery(ec, mconn, statement, ps);
                try {
                    DNStateManager[] missingSMs = processResults(rs, sms);
                    if (missingSMs != null && missingSMs.length > 0) {
                        NucleusObjectNotFoundException[] nfes = new NucleusObjectNotFoundException[missingSMs.length];
                        for (int i = 0; i < nfes.length; i++) {
                            nfes[i] = new NucleusObjectNotFoundException(Localiser.msg("050018", IdentityUtils.getPersistableIdentityForId(missingSMs[i].getInternalObjectId())));
                        }
                        throw new NucleusObjectNotFoundException("Some objects were not found. Look at nested exceptions for details", nfes);
                    }
                } finally {
                    rs.close();
                }
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException sqle) {
        String msg = Localiser.msg("052220", sms[0].getObjectAsPrintable(), statement, sqle.getMessage());
        NucleusLogger.DATASTORE_RETRIEVE.warn(msg);
        List exceptions = new ArrayList();
        exceptions.add(sqle);
        while ((sqle = sqle.getNextException()) != null) {
            exceptions.add(sqle);
        }
        throw new NucleusDataStoreException(msg, (Throwable[]) exceptions.toArray(new Throwable[exceptions.size()]));
    }
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) LockMode(org.datanucleus.state.LockMode) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) ParameterSetter(org.datanucleus.store.rdbms.fieldmanager.ParameterSetter) NucleusObjectNotFoundException(org.datanucleus.exceptions.NucleusObjectNotFoundException) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager) SQLController(org.datanucleus.store.rdbms.SQLController) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) ResultSet(java.sql.ResultSet) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) ArrayList(java.util.ArrayList) List(java.util.List) DNStateManager(org.datanucleus.state.DNStateManager)

Example 10 with NucleusObjectNotFoundException

use of org.datanucleus.exceptions.NucleusObjectNotFoundException in project datanucleus-rdbms by datanucleus.

the class LocateRequest method execute.

/**
 * Method performing the retrieval of the record from the datastore.
 * Takes the constructed retrieval query and populates with the specific record information.
 * @param sm StateManager for the record to be retrieved
 */
public void execute(DNStateManager sm) {
    if (statementLocked != null) {
        ExecutionContext ec = sm.getExecutionContext();
        RDBMSStoreManager storeMgr = table.getStoreManager();
        // Override with pessimistic lock where specified
        LockMode lockType = ec.getLockManager().getLockMode(sm.getInternalObjectId());
        boolean locked = (lockType == LockMode.LOCK_PESSIMISTIC_READ || lockType == LockMode.LOCK_PESSIMISTIC_WRITE) ? true : ec.getSerializeReadForClass(sm.getClassMetaData().getFullClassName());
        String statement = (locked ? statementLocked : statementUnlocked);
        try {
            ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
            SQLController sqlControl = storeMgr.getSQLController();
            try {
                PreparedStatement ps = sqlControl.getStatementForQuery(mconn, statement);
                AbstractClassMetaData cmd = sm.getClassMetaData();
                try {
                    // Provide the primary key field(s)
                    if (cmd.getIdentityType() == IdentityType.DATASTORE) {
                        StatementMappingIndex datastoreIdx = mappingDefinition.getMappingForMemberPosition(SurrogateColumnType.DATASTORE_ID.getFieldNumber());
                        for (int i = 0; i < datastoreIdx.getNumberOfParameterOccurrences(); i++) {
                            table.getSurrogateMapping(SurrogateColumnType.DATASTORE_ID, false).setObject(ec, ps, datastoreIdx.getParameterPositionsForOccurrence(i), sm.getInternalObjectId());
                        }
                    } else if (cmd.getIdentityType() == IdentityType.APPLICATION) {
                        sm.provideFields(cmd.getPKMemberPositions(), new ParameterSetter(sm, ps, mappingDefinition));
                    }
                    JavaTypeMapping multitenancyMapping = table.getSurrogateMapping(SurrogateColumnType.MULTITENANCY, false);
                    if (multitenancyMapping != null) {
                        String[] tenantReadIds = storeMgr.getNucleusContext().getTenantReadIds(sm.getExecutionContext());
                        if (tenantReadIds != null && tenantReadIds.length > 0) {
                        // Using IN clause so nothing to do since hardcoded
                        } else {
                            // Set MultiTenancy tenant id in statement
                            StatementMappingIndex multitenancyIdx = mappingDefinition.getMappingForMemberPosition(SurrogateColumnType.MULTITENANCY.getFieldNumber());
                            String tenantId = ec.getTenantId();
                            for (int i = 0; i < multitenancyIdx.getNumberOfParameterOccurrences(); i++) {
                                multitenancyMapping.setObject(ec, ps, multitenancyIdx.getParameterPositionsForOccurrence(i), tenantId);
                            }
                        }
                    }
                    JavaTypeMapping softDeleteMapping = table.getSurrogateMapping(SurrogateColumnType.SOFTDELETE, false);
                    if (softDeleteMapping != null) {
                        // Set SoftDelete parameter in statement
                        StatementMappingIndex softDeleteIdx = mappingDefinition.getMappingForMemberPosition(SurrogateColumnType.SOFTDELETE.getFieldNumber());
                        for (int i = 0; i < softDeleteIdx.getNumberOfParameterOccurrences(); i++) {
                            softDeleteMapping.setObject(ec, ps, softDeleteIdx.getParameterPositionsForOccurrence(i), Boolean.FALSE);
                        }
                    }
                    // Execute the statement
                    ResultSet rs = sqlControl.executeStatementQuery(ec, mconn, statement, ps);
                    try {
                        if (!rs.next()) {
                            String msg = Localiser.msg("050018", IdentityUtils.getPersistableIdentityForId(sm.getInternalObjectId()));
                            if (NucleusLogger.DATASTORE_RETRIEVE.isInfoEnabled()) {
                                NucleusLogger.DATASTORE_RETRIEVE.info(msg);
                            }
                            throw new NucleusObjectNotFoundException(msg);
                        }
                    } finally {
                        rs.close();
                    }
                } finally {
                    sqlControl.closeStatement(mconn, ps);
                }
            } finally {
                mconn.release();
            }
        } catch (SQLException sqle) {
            String msg = Localiser.msg("052220", IdentityUtils.getPersistableIdentityForId(sm.getInternalObjectId()), statement, sqle.getMessage());
            NucleusLogger.DATASTORE_RETRIEVE.warn(msg);
            List exceptions = new ArrayList();
            exceptions.add(sqle);
            while ((sqle = sqle.getNextException()) != null) {
                exceptions.add(sqle);
            }
            throw new NucleusDataStoreException(msg, (Throwable[]) exceptions.toArray(new Throwable[exceptions.size()]));
        }
    }
}
Also used : JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) LockMode(org.datanucleus.state.LockMode) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) ParameterSetter(org.datanucleus.store.rdbms.fieldmanager.ParameterSetter) NucleusObjectNotFoundException(org.datanucleus.exceptions.NucleusObjectNotFoundException) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager) SQLController(org.datanucleus.store.rdbms.SQLController) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) ResultSet(java.sql.ResultSet) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

NucleusObjectNotFoundException (org.datanucleus.exceptions.NucleusObjectNotFoundException)27 ExecutionContext (org.datanucleus.ExecutionContext)15 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)14 ObjectProvider (org.datanucleus.state.ObjectProvider)12 PreparedStatement (java.sql.PreparedStatement)10 ResultSet (java.sql.ResultSet)10 SQLException (java.sql.SQLException)10 NucleusDataStoreException (org.datanucleus.exceptions.NucleusDataStoreException)10 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)10 ManagedConnection (org.datanucleus.store.connection.ManagedConnection)10 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)10 SQLController (org.datanucleus.store.rdbms.SQLController)10 ParameterSetter (org.datanucleus.store.rdbms.fieldmanager.ParameterSetter)10 StatementMappingIndex (org.datanucleus.store.rdbms.query.StatementMappingIndex)10 ArrayList (java.util.ArrayList)9 List (java.util.List)8 JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)8 ClassLoaderResolver (org.datanucleus.ClassLoaderResolver)6 ApiAdapter (org.datanucleus.api.ApiAdapter)6 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)6