Search in sources :

Example 11 with PreparedStatementCreator

use of org.springframework.jdbc.core.PreparedStatementCreator in project rdbcache by rdbcache.

the class Query method executeInsert.

public boolean executeInsert(boolean enableLocal, boolean enableRedis) {
    params = new ArrayList<>();
    boolean allOk = true;
    for (int i = 0; i < pairs.size(); i++) {
        KvPair pair = pairs.get(i);
        KeyInfo keyInfo = anyKey.getAny(i);
        String table = keyInfo.getTable();
        Map<String, Object> map = pair.getData();
        String autoIncKey = AppCtx.getDbaseOps().getTableAutoIncColumn(context, table);
        boolean cacheUpdate = false;
        if (!map.containsKey(autoIncKey) && keyInfo.getParams() != null && keyInfo.getParams().size() == 1) {
            String stdClause = "(" + autoIncKey + " = ?)";
            if (stdClause.equals(keyInfo.getClause())) {
                map.put(autoIncKey, keyInfo.getParams().get(0));
                cacheUpdate = true;
            }
        }
        Map<String, Object> columns = keyInfo.getColumns();
        AppCtx.getDbaseOps().convertDbMap(columns, map);
        String fields = "", values = "";
        params.clear();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            params.add(entry.getValue());
            if (fields.length() != 0) {
                fields += ", ";
                values += ", ";
            }
            fields += entry.getKey();
            values += "?";
        }
        sql = "insert into " + table + " (" + fields + ") values (" + values + ")";
        LOGGER.trace("sql: " + sql);
        LOGGER.trace("params: " + params.toString());
        int rowCount = 0;
        KeyHolder keyHolder = new GeneratedKeyHolder();
        StopWatch stopWatch = context.startStopWatch("dbase", "jdbcTemplate.update");
        try {
            rowCount = jdbcTemplate.update(new PreparedStatementCreator() {

                @Override
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement ps;
                    ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                    int i = 1;
                    for (Object param : params) {
                        ps.setObject(i++, param);
                    }
                    return ps;
                }
            }, keyHolder);
            if (stopWatch != null)
                stopWatch.stopNow();
        } catch (Exception e) {
            if (stopWatch != null)
                stopWatch.stopNow();
            allOk = false;
            String msg = e.getCause().getMessage();
            LOGGER.error(msg);
            context.logTraceMessage(msg);
            if (context.isSync()) {
                throw new ServerErrorException(context, msg);
            }
        }
        if (rowCount > 0) {
            if (autoIncKey != null && keyHolder.getKey() != null) {
                String keyValue = String.valueOf(keyHolder.getKey());
                map.put(autoIncKey, keyValue);
                cacheUpdate = true;
            }
            if (cacheUpdate) {
                if (enableLocal) {
                    AppCtx.getLocalCache().putData(pair, keyInfo);
                }
                if (enableRedis) {
                    AppCtx.getRedisRepo().save(context, new KvPairs(pair), new AnyKey(keyInfo));
                }
            }
            if (!Parser.prepareStandardClauseParams(context, pair, keyInfo)) {
                String msg = "executeInsert failed when prepareStandardClauseParams for " + pair.getId();
                LOGGER.error(msg);
                context.logTraceMessage(msg);
                if (context.isSync()) {
                    throw new ServerErrorException(context, msg);
                }
            }
            LOGGER.trace("inserted " + pair.getId() + " into " + table);
        } else {
            allOk = false;
            LOGGER.warn("failed to insert " + pair.getId() + " into " + table);
        }
    }
    return allOk;
}
Also used : AnyKey(com.rdbcache.helpers.AnyKey) KvPair(com.rdbcache.models.KvPair) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) KvPairs(com.rdbcache.helpers.KvPairs) KeyHolder(org.springframework.jdbc.support.KeyHolder) GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) ServerErrorException(com.rdbcache.exceptions.ServerErrorException) SQLException(java.sql.SQLException) StopWatch(com.rdbcache.models.StopWatch) GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) KeyInfo(com.rdbcache.models.KeyInfo) PreparedStatementCreator(org.springframework.jdbc.core.PreparedStatementCreator) ServerErrorException(com.rdbcache.exceptions.ServerErrorException)

Example 12 with PreparedStatementCreator

use of org.springframework.jdbc.core.PreparedStatementCreator in project leopard by tanhaichao.

the class JdbcMysqlImpl method insertForLastId.

@Override
public long insertForLastId(final String sql, final StatementParameter param) {
    GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
    this.getJdbcTemplate().update(new PreparedStatementCreator() {

        @Override
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement pstmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            param.setValues(pstmt);
            return pstmt;
        }
    }, keyHolder);
    return keyHolder.getKey().longValue();
}
Also used : GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) SQLException(java.sql.SQLException) PreparedStatementCreator(org.springframework.jdbc.core.PreparedStatementCreator) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement)

Example 13 with PreparedStatementCreator

use of org.springframework.jdbc.core.PreparedStatementCreator in project training_portal by training-portal.

the class GroupDaoJdbc method addGroup.

@Transactional
@Override
public Long addGroup(Group group) {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    template.update(new PreparedStatementCreator() {

        @Override
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement stmt = con.prepareStatement(ADD_GROUP, new String[] { "group_id" });
            stmt.setString(1, group.getName());
            stmt.setString(2, group.getDescription());
            stmt.setDate(3, Date.valueOf(group.getCreationDate()));
            stmt.setLong(4, group.getAuthorId());
            return stmt;
        }
    }, keyHolder);
    long groupId = keyHolder.getKey().longValue();
    group.setGroupId(groupId);
    logger.info("Group added: " + group);
    return groupId;
}
Also used : GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) PreparedStatementCreator(org.springframework.jdbc.core.PreparedStatementCreator) KeyHolder(org.springframework.jdbc.support.KeyHolder) GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) Transactional(org.springframework.transaction.annotation.Transactional)

Example 14 with PreparedStatementCreator

use of org.springframework.jdbc.core.PreparedStatementCreator in project rdbcache by rdbcache.

the class MonitorRepoImpl method save.

@Override
public void save(Monitor monitor) {
    Map<String, Object> map = Utils.toMap(monitor);
    String fields = "";
    String values = "";
    final List<Object> params1 = new ArrayList<>();
    for (Map.Entry<String, Object> entry : map.entrySet()) {
        params1.add(entry.getValue());
        if (fields.length() != 0) {
            fields += ", ";
            values += ", ";
        }
        fields += entry.getKey();
        values += "?";
    }
    final String sql1 = "insert into " + monitorTable + " (" + fields + ") values (" + values + ")";
    int result = 0;
    KeyHolder keyHolder = new GeneratedKeyHolder();
    try {
        result = jdbcTemplate.update(new PreparedStatementCreator() {

            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps;
                ps = connection.prepareStatement(sql1, Statement.RETURN_GENERATED_KEYS);
                int i = 1;
                for (Object param : params1) {
                    ps.setObject(i++, param);
                }
                return ps;
            }
        }, keyHolder);
    } catch (Exception e) {
        e.getStackTrace();
        return;
    }
    if (result == 0) {
        return;
    }
    Long id = Long.valueOf(keyHolder.getKey().toString());
    List<StopWatch> watches = monitor.getStopWatches();
    if (watches != null && watches.size() > 0) {
        map = AppCtx.getDbaseOps().getTableColumns(null, stopWatchTable);
        Set<String> keySet = map.keySet();
        fields = "";
        values = "";
        for (String key : keySet) {
            if (fields.length() != 0) {
                fields += ", ";
                values += ", ";
            }
            fields += key;
            values += "?";
        }
        final String sql2 = "insert into " + monitorTable + "(" + fields + ") values (" + values + ")";
        List<Object[]> paramsList = new ArrayList<Object[]>();
        for (StopWatch watch : watches) {
            watch.setMonitorId(id);
            map = Utils.toMap(watch);
            List<Object> params = new ArrayList<>();
            for (String key : keySet) {
                if (map.containsKey(key)) {
                    params.add(map.get(key));
                } else {
                    params.add(null);
                }
            }
            paramsList.add(params.toArray());
        }
        jdbcTemplate.batchUpdate(sql2, paramsList);
    }
}
Also used : ArrayList(java.util.ArrayList) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) KeyHolder(org.springframework.jdbc.support.KeyHolder) GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) SQLException(java.sql.SQLException) StopWatch(doitincloud.rdbcache.models.StopWatch) GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) PreparedStatementCreator(org.springframework.jdbc.core.PreparedStatementCreator) Map(java.util.Map)

Example 15 with PreparedStatementCreator

use of org.springframework.jdbc.core.PreparedStatementCreator in project buffer-slayer by tramchamploo.

the class BatchJdbcTemplateTest method updateWithPreparedStatementCreator.

@Test
public void updateWithPreparedStatementCreator() {
    reporter = AsyncReporter.builder(new JdbcTemplateSender(underlying)).pendingMaxMessages(2).bufferedMaxMessages(2).messageTimeout(0, TimeUnit.MILLISECONDS).build();
    batchJdbcTemplate = new BatchJdbcTemplate(underlying, reporter);
    PreparedStatementCreatorFactory creatorFactory = new PreparedStatementCreatorFactory(INSERTION);
    creatorFactory.addParameter(new SqlParameter(Types.VARCHAR));
    creatorFactory.addParameter(new SqlParameter(Types.TIMESTAMP));
    PreparedStatementCreator creator = creatorFactory.newPreparedStatementCreator(new Object[] { randomString(), new Date() });
    batchJdbcTemplate.update(creator);
    batchJdbcTemplate.update(creator);
    reporter.flush();
    int rowCount = batchJdbcTemplate.queryForObject("SELECT COUNT(1) FROM test;", Integer.class);
    assertEquals(2, rowCount);
}
Also used : SqlParameter(org.springframework.jdbc.core.SqlParameter) PreparedStatementCreator(org.springframework.jdbc.core.PreparedStatementCreator) Date(java.util.Date) PreparedStatementCreatorFactory(org.springframework.jdbc.core.PreparedStatementCreatorFactory) Test(org.junit.Test)

Aggregations

PreparedStatementCreator (org.springframework.jdbc.core.PreparedStatementCreator)19 GeneratedKeyHolder (org.springframework.jdbc.support.GeneratedKeyHolder)16 KeyHolder (org.springframework.jdbc.support.KeyHolder)14 Connection (java.sql.Connection)12 PreparedStatement (java.sql.PreparedStatement)12 SQLException (java.sql.SQLException)10 Transactional (org.springframework.transaction.annotation.Transactional)5 Map (java.util.Map)3 BaseObject (com.github.knightliao.apollo.db.bo.BaseObject)2 StopWatch (doitincloud.rdbcache.models.StopWatch)2 List (java.util.List)2 Test (org.junit.Test)2 EmptyResultDataAccessException (org.springframework.dao.EmptyResultDataAccessException)2 PreparedStatementCreatorFactory (org.springframework.jdbc.core.PreparedStatementCreatorFactory)2 SqlParameter (org.springframework.jdbc.core.SqlParameter)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 ServerErrorException (com.rdbcache.exceptions.ServerErrorException)1 AnyKey (com.rdbcache.helpers.AnyKey)1 KvPairs (com.rdbcache.helpers.KvPairs)1