Search in sources :

Example 96 with DataAccessException

use of org.springframework.dao.DataAccessException in project spring-data-mongodb by spring-projects.

the class MongoTemplate method doUpdate.

protected UpdateResult doUpdate(final String collectionName, final Query query, final Update update, @Nullable final Class<?> entityClass, final boolean upsert, final boolean multi) {
    Assert.notNull(collectionName, "CollectionName must not be null!");
    Assert.notNull(query, "Query must not be null!");
    Assert.notNull(update, "Update must not be null!");
    return execute(collectionName, new CollectionCallback<UpdateResult>() {

        public UpdateResult doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
            MongoPersistentEntity<?> entity = entityClass == null ? null : getPersistentEntity(entityClass);
            increaseVersionForUpdateIfNecessary(entity, update);
            UpdateOptions opts = new UpdateOptions();
            opts.upsert(upsert);
            Document queryObj = new Document();
            if (query != null) {
                queryObj.putAll(queryMapper.getMappedObject(query.getQueryObject(), entity));
                query.getCollation().map(Collation::toMongoCollation).ifPresent(opts::collation);
            }
            Document updateObj = update == null ? new Document() : updateMapper.getMappedObject(update.getUpdateObject(), entity);
            if (multi && update.isIsolated() && !queryObj.containsKey("$isolated")) {
                queryObj.put("$isolated", 1);
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Calling update using query: {} and update: {} in collection: {}", serializeToJsonSafely(queryObj), serializeToJsonSafely(updateObj), collectionName);
            }
            MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName, entityClass, updateObj, queryObj);
            WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
            collection = writeConcernToUse != null ? collection.withWriteConcern(writeConcernToUse) : collection;
            if (!UpdateMapper.isUpdateObject(updateObj)) {
                return collection.replaceOne(queryObj, updateObj, opts);
            } else {
                if (multi) {
                    return collection.updateMany(queryObj, updateObj, opts);
                } else {
                    return collection.updateOne(queryObj, updateObj, opts);
                }
            }
        }
    });
}
Also used : MongoException(com.mongodb.MongoException) MongoPersistentEntity(org.springframework.data.mongodb.core.mapping.MongoPersistentEntity) WriteConcern(com.mongodb.WriteConcern) Document(org.bson.Document) Collation(org.springframework.data.mongodb.core.query.Collation) UpdateResult(com.mongodb.client.result.UpdateResult) DataAccessException(org.springframework.dao.DataAccessException)

Example 97 with DataAccessException

use of org.springframework.dao.DataAccessException in project spring-data-mongodb by spring-projects.

the class MongoChangeSetPersister method getPersistentState.

/*
	 * (non-Javadoc)
	 * @see org.springframework.data.crossstore.ChangeSetPersister#getPersistentState(java.lang.Class, java.lang.Object, org.springframework.data.crossstore.ChangeSet)
	 */
public void getPersistentState(Class<? extends ChangeSetBacked> entityClass, Object id, final ChangeSet changeSet) throws DataAccessException, NotFoundException {
    if (id == null) {
        log.debug("Unable to load MongoDB data for null id");
        return;
    }
    String collName = getCollectionNameForEntity(entityClass);
    final Document dbk = new Document();
    dbk.put(ENTITY_ID, id);
    dbk.put(ENTITY_CLASS, entityClass.getName());
    if (log.isDebugEnabled()) {
        log.debug("Loading MongoDB data for {}", dbk);
    }
    mongoTemplate.execute(collName, new CollectionCallback<Object>() {

        public Object doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
            for (Document dbo : collection.find(dbk)) {
                String key = (String) dbo.get(ENTITY_FIELD_NAME);
                if (log.isDebugEnabled()) {
                    log.debug("Processing key: {}", key);
                }
                if (!changeSet.getValues().containsKey(key)) {
                    String className = (String) dbo.get(ENTITY_FIELD_CLASS);
                    if (className == null) {
                        throw new DataIntegrityViolationException("Unble to convert property " + key + ": Invalid metadata, " + ENTITY_FIELD_CLASS + " not available");
                    }
                    Class<?> clazz = ClassUtils.resolveClassName(className, ClassUtils.getDefaultClassLoader());
                    Object value = mongoTemplate.getConverter().read(clazz, dbo);
                    if (log.isDebugEnabled()) {
                        log.debug("Adding to ChangeSet: {}", key);
                    }
                    changeSet.set(key, value);
                }
            }
            return null;
        }
    });
}
Also used : MongoException(com.mongodb.MongoException) Document(org.bson.Document) DataAccessException(org.springframework.dao.DataAccessException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException)

Example 98 with DataAccessException

use of org.springframework.dao.DataAccessException in project spring-data-mongodb by spring-projects.

the class MongoChangeSetPersister method persistState.

/*
	 * (non-Javadoc)
	 * @see org.springframework.data.crossstore.ChangeSetPersister#persistState(org.springframework.data.crossstore.ChangeSetBacked, org.springframework.data.crossstore.ChangeSet)
	 */
public Object persistState(ChangeSetBacked entity, ChangeSet cs) throws DataAccessException {
    if (cs == null) {
        log.debug("Flush: changeset was null, nothing to flush.");
        return 0L;
    }
    if (log.isDebugEnabled()) {
        log.debug("Flush: changeset: {}", cs.getValues());
    }
    String collName = getCollectionNameForEntity(entity.getClass());
    if (mongoTemplate.getCollection(collName) == null) {
        mongoTemplate.createCollection(collName);
    }
    for (String key : cs.getValues().keySet()) {
        if (key != null && !key.startsWith("_") && !key.equals(ChangeSetPersister.ID_KEY)) {
            Object value = cs.getValues().get(key);
            final Document dbQuery = new Document();
            dbQuery.put(ENTITY_ID, getPersistentId(entity, cs));
            dbQuery.put(ENTITY_CLASS, entity.getClass().getName());
            dbQuery.put(ENTITY_FIELD_NAME, key);
            final Document dbId = mongoTemplate.execute(collName, new CollectionCallback<Document>() {

                public Document doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
                    Document id = collection.find(dbQuery).first();
                    return id;
                }
            });
            if (value == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Flush: removing: {}", dbQuery);
                }
                mongoTemplate.execute(collName, new CollectionCallback<Object>() {

                    public Object doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
                        DeleteResult dr = collection.deleteMany(dbQuery);
                        return null;
                    }
                });
            } else {
                final Document dbDoc = new Document();
                dbDoc.putAll(dbQuery);
                if (log.isDebugEnabled()) {
                    log.debug("Flush: saving: {}", dbQuery);
                }
                mongoTemplate.getConverter().write(value, dbDoc);
                dbDoc.put(ENTITY_FIELD_CLASS, value.getClass().getName());
                if (dbId != null) {
                    dbDoc.put("_id", dbId.get("_id"));
                }
                mongoTemplate.execute(collName, new CollectionCallback<Object>() {

                    public Object doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
                        if (dbId != null) {
                            collection.replaceOne(Filters.eq("_id", dbId.get("_id")), dbDoc);
                        } else {
                            if (dbDoc.containsKey("_id") && dbDoc.get("_id") == null) {
                                dbDoc.remove("_id");
                            }
                            collection.insertOne(dbDoc);
                        }
                        return null;
                    }
                });
            }
        }
    }
    return 0L;
}
Also used : MongoException(com.mongodb.MongoException) Document(org.bson.Document) DataAccessException(org.springframework.dao.DataAccessException) DeleteResult(com.mongodb.client.result.DeleteResult)

Example 99 with DataAccessException

use of org.springframework.dao.DataAccessException in project camel by apache.

the class ElsqlSqlProcessingStrategy method commitBatchComplete.

@Override
public int commitBatchComplete(DefaultSqlEndpoint endpoint, NamedParameterJdbcTemplate namedJdbcTemplate, SqlParameterSource parameterSource, String query) throws Exception {
    final SqlParameterSource param = new EmptySqlParameterSource();
    final String sql = elSql.getSql(query, new SpringSqlParams(param));
    LOG.debug("commitBatchComplete @{} using sql: {}", query, sql);
    return namedJdbcTemplate.execute(sql, param, new PreparedStatementCallback<Integer>() {

        @Override
        public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ps.execute();
            int updateCount = ps.getUpdateCount();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Update count {}", updateCount);
            }
            return updateCount;
        }
    });
}
Also used : EmptySqlParameterSource(org.springframework.jdbc.core.namedparam.EmptySqlParameterSource) SqlParameterSource(org.springframework.jdbc.core.namedparam.SqlParameterSource) SQLException(java.sql.SQLException) EmptySqlParameterSource(org.springframework.jdbc.core.namedparam.EmptySqlParameterSource) PreparedStatement(java.sql.PreparedStatement) DataAccessException(org.springframework.dao.DataAccessException) SpringSqlParams(com.opengamma.elsql.SpringSqlParams)

Example 100 with DataAccessException

use of org.springframework.dao.DataAccessException in project opennms by OpenNMS.

the class Correlation method format.

/**
 * Format the correlation block to have the xml
 *
 * @param ec
 *            the correlation
 * @param sz
 *            the size to which the formatted string is to be limited
 *            to(usually the size of the column in the database)
 * @return the formatted event correlation
 */
public static String format(final org.opennms.netmgt.xml.event.Correlation ec, final int sz) {
    StringWriter out = new StringWriter();
    try {
        JaxbUtils.marshal(ec, out);
    } catch (DataAccessException e) {
        LOG.error("Failed to convert new event to XML", e);
        return null;
    }
    String outstr = out.toString();
    if (outstr.length() >= sz) {
        final StringBuilder buf = new StringBuilder(outstr);
        buf.setLength(sz - 4);
        buf.append(EventDatabaseConstants.VALUE_TRUNCATE_INDICATOR);
        return buf.toString();
    } else {
        return outstr;
    }
}
Also used : StringWriter(java.io.StringWriter) DataAccessException(org.springframework.dao.DataAccessException)

Aggregations

DataAccessException (org.springframework.dao.DataAccessException)154 SQLException (java.sql.SQLException)50 ResultSet (java.sql.ResultSet)22 Connection (java.sql.Connection)18 PreparedStatement (java.sql.PreparedStatement)17 Test (org.junit.jupiter.api.Test)17 MongoException (com.mongodb.MongoException)14 IOException (java.io.IOException)14 ArrayList (java.util.ArrayList)14 List (java.util.List)13 HashMap (java.util.HashMap)11 Map (java.util.Map)11 Transactional (org.springframework.transaction.annotation.Transactional)11 JdbcTemplate (org.springframework.jdbc.core.JdbcTemplate)10 Document (org.bson.Document)9 Test (org.junit.Test)9 Logger (org.slf4j.Logger)9 LoggerFactory (org.slf4j.LoggerFactory)9 RedisConnection (org.springframework.data.redis.connection.RedisConnection)7 RedisCallback (org.springframework.data.redis.core.RedisCallback)7