Search in sources :

Example 1 with BatchPreparedStatementSetter

use of org.springframework.jdbc.core.BatchPreparedStatementSetter in project TranslateIt-api by zunpiau.

the class WordbookRepositoryImpl method save.

@Override
public int save(long uid, List<Wordbook> wordbooks) {
    return template.batchUpdate("INSERT INTO wordbook ( uid, " + WORDBOOK_FILED + " ) VALUES(?,?,?,?,?,?,?,?,?,?,?)", new BatchPreparedStatementSetter() {

        @Override
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            Wordbook wordbook = wordbooks.get(i);
            ps.setLong(1, uid);
            ps.setString(2, wordbook.getWord());
            ps.setString(3, wordbook.getPhEn());
            ps.setString(4, wordbook.getPhAm());
            ps.setString(5, wordbook.getPhEnUrl());
            ps.setString(6, wordbook.getPhAmUrl());
            ps.setString(7, wordbook.getMean());
            ps.setString(8, wordbook.getExchange());
            ps.setString(9, wordbook.getSentence());
            ps.setString(10, wordbook.getNote());
            ps.setString(11, wordbook.getCategory());
        }

        @Override
        public int getBatchSize() {
            return wordbooks.size();
        }
    }).length;
}
Also used : Wordbook(zjp.translateit.domain.Wordbook) ModifyWordbook(zjp.translateit.dto.ModifyWordbook) BatchPreparedStatementSetter(org.springframework.jdbc.core.BatchPreparedStatementSetter) PreparedStatement(java.sql.PreparedStatement)

Example 2 with BatchPreparedStatementSetter

use of org.springframework.jdbc.core.BatchPreparedStatementSetter in project TranslateIt-api by zunpiau.

the class WordbookRepositoryImpl method update.

public int update(long uid, List<ModifyWordbook> wordbooks) {
    return template.batchUpdate("UPDATE wordbook SET note = ?, category = ? WHERE uid = ? AND word = ? ", new BatchPreparedStatementSetter() {

        @Override
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            ModifyWordbook wordbook = wordbooks.get(i);
            ps.setString(1, wordbook.getNote());
            ps.setString(2, wordbook.getCategory());
            ps.setLong(3, uid);
            ps.setString(4, wordbook.getWord());
        }

        @Override
        public int getBatchSize() {
            return wordbooks.size();
        }
    }).length;
}
Also used : BatchPreparedStatementSetter(org.springframework.jdbc.core.BatchPreparedStatementSetter) ModifyWordbook(zjp.translateit.dto.ModifyWordbook) PreparedStatement(java.sql.PreparedStatement)

Example 3 with BatchPreparedStatementSetter

use of org.springframework.jdbc.core.BatchPreparedStatementSetter in project spring-session by spring-projects.

the class JdbcOperationsSessionRepository method save.

@Override
public void save(final JdbcSession session) {
    if (session.isNew()) {
        this.transactionOperations.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                JdbcOperationsSessionRepository.this.jdbcOperations.update(JdbcOperationsSessionRepository.this.createSessionQuery, ps -> {
                    ps.setString(1, session.primaryKey);
                    ps.setString(2, session.getId());
                    ps.setLong(3, session.getCreationTime().toEpochMilli());
                    ps.setLong(4, session.getLastAccessedTime().toEpochMilli());
                    ps.setInt(5, (int) session.getMaxInactiveInterval().getSeconds());
                    ps.setLong(6, session.getExpiryTime().toEpochMilli());
                    ps.setString(7, session.getPrincipalName());
                });
                if (!session.getAttributeNames().isEmpty()) {
                    final List<String> attributeNames = new ArrayList<>(session.getAttributeNames());
                    JdbcOperationsSessionRepository.this.jdbcOperations.batchUpdate(JdbcOperationsSessionRepository.this.createSessionAttributeQuery, new BatchPreparedStatementSetter() {

                        @Override
                        public void setValues(PreparedStatement ps, int i) throws SQLException {
                            String attributeName = attributeNames.get(i);
                            ps.setString(1, session.primaryKey);
                            ps.setString(2, attributeName);
                            serialize(ps, 3, session.getAttribute(attributeName));
                        }

                        @Override
                        public int getBatchSize() {
                            return attributeNames.size();
                        }
                    });
                }
            }
        });
    } else {
        this.transactionOperations.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                if (session.isChanged()) {
                    JdbcOperationsSessionRepository.this.jdbcOperations.update(JdbcOperationsSessionRepository.this.updateSessionQuery, ps -> {
                        ps.setString(1, session.getId());
                        ps.setLong(2, session.getLastAccessedTime().toEpochMilli());
                        ps.setInt(3, (int) session.getMaxInactiveInterval().getSeconds());
                        ps.setLong(4, session.getExpiryTime().toEpochMilli());
                        ps.setString(5, session.getPrincipalName());
                        ps.setString(6, session.primaryKey);
                    });
                }
                Map<String, Object> delta = session.getDelta();
                if (!delta.isEmpty()) {
                    for (final Map.Entry<String, Object> entry : delta.entrySet()) {
                        if (entry.getValue() == null) {
                            JdbcOperationsSessionRepository.this.jdbcOperations.update(JdbcOperationsSessionRepository.this.deleteSessionAttributeQuery, ps -> {
                                ps.setString(1, session.primaryKey);
                                ps.setString(2, entry.getKey());
                            });
                        } else {
                            int updatedCount = JdbcOperationsSessionRepository.this.jdbcOperations.update(JdbcOperationsSessionRepository.this.updateSessionAttributeQuery, ps -> {
                                serialize(ps, 1, entry.getValue());
                                ps.setString(2, session.primaryKey);
                                ps.setString(3, entry.getKey());
                            });
                            if (updatedCount == 0) {
                                JdbcOperationsSessionRepository.this.jdbcOperations.update(JdbcOperationsSessionRepository.this.createSessionAttributeQuery, ps -> {
                                    ps.setString(1, session.primaryKey);
                                    ps.setString(2, entry.getKey());
                                    serialize(ps, 3, entry.getValue());
                                });
                            }
                        }
                    }
                }
            }
        });
    }
    session.clearChangeFlags();
}
Also used : BatchPreparedStatementSetter(org.springframework.jdbc.core.BatchPreparedStatementSetter) DataAccessException(org.springframework.dao.DataAccessException) JdbcOperations(org.springframework.jdbc.core.JdbcOperations) TransactionDefinition(org.springframework.transaction.TransactionDefinition) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) LobHandler(org.springframework.jdbc.support.lob.LobHandler) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) TypeDescriptor(org.springframework.core.convert.TypeDescriptor) Duration(java.time.Duration) Map(java.util.Map) DeserializingConverter(org.springframework.core.serializer.support.DeserializingConverter) DefaultLobHandler(org.springframework.jdbc.support.lob.DefaultLobHandler) FindByIndexNameSessionRepository(org.springframework.session.FindByIndexNameSessionRepository) ConversionService(org.springframework.core.convert.ConversionService) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) Set(java.util.Set) GenericConversionService(org.springframework.core.convert.support.GenericConversionService) Session(org.springframework.session.Session) UUID(java.util.UUID) PreparedStatement(java.sql.PreparedStatement) Instant(java.time.Instant) SerializingConverter(org.springframework.core.serializer.support.SerializingConverter) List(java.util.List) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) TransactionOperations(org.springframework.transaction.support.TransactionOperations) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) Expression(org.springframework.expression.Expression) TransactionStatus(org.springframework.transaction.TransactionStatus) Log(org.apache.commons.logging.Log) SpelExpressionParser(org.springframework.expression.spel.standard.SpelExpressionParser) LogFactory(org.apache.commons.logging.LogFactory) MapSession(org.springframework.session.MapSession) Collections(java.util.Collections) ResultSetExtractor(org.springframework.jdbc.core.ResultSetExtractor) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) BatchPreparedStatementSetter(org.springframework.jdbc.core.BatchPreparedStatementSetter) TransactionStatus(org.springframework.transaction.TransactionStatus) ArrayList(java.util.ArrayList) List(java.util.List) PreparedStatement(java.sql.PreparedStatement) HashMap(java.util.HashMap) Map(java.util.Map) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult)

Example 4 with BatchPreparedStatementSetter

use of org.springframework.jdbc.core.BatchPreparedStatementSetter in project perun by CESNET.

the class Auditer method storeMessagesToDb.

/**
 * Stores the list of AuditerMessages to the DB in batch.
 *
 * It also checks if there are any messages which can be resolved by registered attribute modules.
 * Store these resolved messages too.
 *
 * @param auditerMessages list of AuditerMessages
 */
public void storeMessagesToDb(final List<AuditerMessage> auditerMessages) {
    // Avoid working with empty list of auditer-messages
    if (auditerMessages == null || auditerMessages.isEmpty()) {
        log.trace("Trying to store empty list of messages to DB!");
        return;
    }
    synchronized (LOCK_DB_TABLE_AUDITER_LOG) {
        // Resolve all additional message from attribute modules and add them to the bulk
        try {
            // Get perun session from the first message (all sessions should be same from the same principal)
            PerunSessionImpl session = (PerunSessionImpl) auditerMessages.get(0).getOriginatingSession();
            // Check recursively all messages if they can create any resolving message
            auditerMessages.addAll(checkRegisteredAttributesModules(session, auditerMessages, new LinkedHashSet<>()));
        } catch (Throwable ex) {
            log.error("There is a problem with processing resolving messages! It will be forcibly skipped to prevent unexpected behavior of auditer log!", ex);
        }
        // Write all messages to the database
        try {
            jdbc.batchUpdate("insert into auditer_log (id, msg, actor, created_at, created_by_uid) values (" + Compatibility.getSequenceNextval("auditer_log_id_seq") + ",?,?," + Compatibility.getSysdate() + ",?)", new BatchPreparedStatementSetter() {

                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    final AuditerMessage auditerMessage = auditerMessages.get(i);
                    final PerunSession session = auditerMessage.getOriginatingSession();
                    String jsonString = "";
                    try {
                        jsonString = mapper.writeValueAsString(auditerMessage.getEvent());
                    } catch (IOException e) {
                        log.error("Could not map event {} to JSON: {}", auditerMessage.getEvent().getClass().getSimpleName(), auditerMessage.getEvent().getMessage());
                    }
                    log.info("AUDIT_JSON: {}", jsonString);
                    ps.setString(1, jsonString);
                    ps.setString(2, session.getPerunPrincipal().getActor());
                    ps.setInt(3, session.getPerunPrincipal().getUserId());
                }

                @Override
                public int getBatchSize() {
                    return auditerMessages.size();
                }
            });
        } catch (InternalErrorException e) {
            log.error("Could not get system date identifier for the DB", e);
        } catch (RuntimeException e) {
            log.error("Cannot store auditer log json message in batch for list ['{}'], exception: {}", auditerMessages, e);
        }
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) PerunSession(cz.metacentrum.perun.core.api.PerunSession) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) BatchPreparedStatementSetter(org.springframework.jdbc.core.BatchPreparedStatementSetter)

Example 5 with BatchPreparedStatementSetter

use of org.springframework.jdbc.core.BatchPreparedStatementSetter in project SSM by Intel-bigdata.

the class FileDiffDao method batchUpdate.

public int[] batchUpdate(final List<Long> dids, final List<FileDiffState> states, final List<String> parameters) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    final String sql = "UPDATE " + TABLE_NAME + " SET state = ?, " + "parameters = ? WHERE did = ?";
    return jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {

        @Override
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            ps.setShort(1, (short) states.get(i).getValue());
            ps.setString(2, parameters.get(i));
            ps.setLong(3, dids.get(i));
        }

        @Override
        public int getBatchSize() {
            return dids.size();
        }
    });
}
Also used : SQLException(java.sql.SQLException) BatchPreparedStatementSetter(org.springframework.jdbc.core.BatchPreparedStatementSetter) PreparedStatement(java.sql.PreparedStatement) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate)

Aggregations

PreparedStatement (java.sql.PreparedStatement)25 BatchPreparedStatementSetter (org.springframework.jdbc.core.BatchPreparedStatementSetter)25 SQLException (java.sql.SQLException)22 JdbcTemplate (org.springframework.jdbc.core.JdbcTemplate)18 NamedParameterJdbcTemplate (org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate)5 ArrayList (java.util.ArrayList)3 TransactionStatus (org.springframework.transaction.TransactionStatus)3 List (java.util.List)2 TransactionCallback (org.springframework.transaction.support.TransactionCallback)2 TransactionTemplate (org.springframework.transaction.support.TransactionTemplate)2 ModifyWordbook (zjp.translateit.dto.ModifyWordbook)2 BaseDbTest (com.alibaba.otter.node.etl.BaseDbTest)1 DbDialect (com.alibaba.otter.node.etl.common.db.dialect.DbDialect)1 DbDataMedia (com.alibaba.otter.shared.common.model.config.data.db.DbDataMedia)1 DbMediaSource (com.alibaba.otter.shared.common.model.config.data.db.DbMediaSource)1 NamedThreadFactory (com.alibaba.otter.shared.common.utils.thread.NamedThreadFactory)1 Query (com.baidu.unbiz.common.genericdao.operator.Query)1 BaseObject (com.github.knightliao.apollo.db.bo.BaseObject)1 EmailRecipient (com.serotonin.m2m2.vo.mailingList.EmailRecipient)1 PerunSession (cz.metacentrum.perun.core.api.PerunSession)1