Example usage for org.springframework.jdbc.core CallableStatementCallback CallableStatementCallback

List of usage examples for org.springframework.jdbc.core CallableStatementCallback CallableStatementCallback

Introduction

In this page you can find the example usage for org.springframework.jdbc.core CallableStatementCallback CallableStatementCallback.

Prototype

CallableStatementCallback

Source Link

Usage

From source file:org.marccarre.spring.db.testing.FooDao.java

public List<Foo> getByIdCallableStatement(int id) {
    final int fooId = id;
    return jdbcTemplate.execute(new CallableStatementCreator() {
        public CallableStatement createCallableStatement(Connection con) throws SQLException {
            CallableStatement cs = con.prepareCall("{call GetFoosById(?)}");
            cs.setInt(1, fooId);//ww w .ja  va 2  s .  c  o m
            return cs;
        }
    }, new CallableStatementCallback<List<Foo>>() {
        public List<Foo> doInCallableStatement(CallableStatement cs) throws SQLException {
            cs.execute();
            List<Foo> foos = new ArrayList<Foo>();

            if (cs.getMoreResults()) {
                ResultSet rs = cs.getResultSet();
                FooRowMapper mapper = new FooRowMapper();
                int rowIndex = 0;
                while (rs.next()) {
                    foos.add(mapper.mapRow(rs, rowIndex));
                    rowIndex++;
                }
            }

            return foos;
        }
    });
}

From source file:com.nortal.petit.core.dialect.OracleSqlDialect.java

@SuppressWarnings("unchecked")
@Override/*www. j  ava 2 s.co  m*/
public <B> B insertReturningId(JdbcOperations jdbcOperations, String sql, String idColumn,
        final Object... params) {
    final String actualSql = new StringBuilder("BEGIN ").append(sql)
            .append(" RETURNING " + idColumn + " INTO ?; END;").toString();
    try {
        return (B) jdbcOperations.execute(new CallableStatementCreator() {
            @Override
            public CallableStatement createCallableStatement(Connection con) throws SQLException {
                CallableStatement cs = con.prepareCall(actualSql);
                ArgPreparedStatementSetter.setValues(cs, params, 1);
                cs.registerOutParameter(params.length + 1, Types.DECIMAL);
                return cs;
            }
        }, new CallableStatementCallback<B>() {
            @Override
            public B doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
                cs.execute();
                BigDecimal bd = cs.getBigDecimal(params.length + 1);
                return (B) Long.valueOf(bd.longValue());
            }
        });
    } catch (RuntimeException e) {
        LOG.error("Error processing SQL '" + sql + "' with parameters: " + StringUtils.join(params, "; "));
        throw e;
    }
}

From source file:net.solarnetwork.node.dao.jdbc.derby.DerbyCompressTableJob.java

@Override
protected void executeInternal(JobExecutionContext jobContext) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("Compressing Derby table " + schema + '.' + table + " with purgeRows = " + purgeRows
                + ", defragmentRows = " + defragmentRows + ", truncateEnd = " + truncateEnd);
    }// w  w  w . j  ava 2  s.  com
    jdbcOperations.execute(new CallableStatementCreator() {
        public CallableStatement createCallableStatement(Connection con) throws SQLException {
            if (log.isTraceEnabled()) {
                log.trace("Preparing Derby compress table call [" + COMPRESS_CALL + ']');
            }
            return con.prepareCall(COMPRESS_CALL);
        }
    }, new CallableStatementCallback<Object>() {
        public Object doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
            int idx = 1;
            cs.setString(idx++, schema);
            cs.setString(idx++, table);
            cs.setShort(idx++, purgeRows ? (short) 1 : (short) 0);
            cs.setShort(idx++, defragmentRows ? (short) 1 : (short) 0);
            cs.setShort(idx++, truncateEnd ? (short) 1 : (short) 0);
            boolean result = cs.execute();
            if (log.isTraceEnabled()) {
                log.trace("Derby compress table call returned [" + result + ']');
            }
            return null;
        }
    });
    if (log.isInfoEnabled()) {
        log.info("Compressed Derby table " + schema + '.' + table);
    }
}

From source file:com.jbrisbin.vpc.jobsched.sql.SqlMessageHandler.java

public SqlMessage handleMessage(final SqlMessage msg) throws Exception {
    log.debug("handling message: " + msg.toString());

    DataSource ds = appCtx.getBean(msg.getDatasource(), DataSource.class);
    JdbcTemplate tmpl = new JdbcTemplate(ds);

    String sql = msg.getSql();//from w w w .j a  va2  s  . c o  m
    CallableStatementCreator stmtCreator = null;
    CallableStatementCallback<SqlMessage> callback = null;
    if (sql.startsWith("plugin:")) {
        // Use a plugin to get the sql
        String pluginName = (sql.contains("?") ? sql.substring(7, sql.indexOf('?')) : sql.substring(7));
        final Plugin plugin = groovyPluginManager.getPlugin(pluginName);
        Map<String, Object> vars = new LinkedHashMap<String, Object>();
        vars.put("message", msg);
        vars.put("datasource", ds);
        vars.put("listen", groovyClosureFactory.createListenClosure(msg));
        vars.put("mapreduce", groovyClosureFactory.createMapReduceClosure(msg));
        plugin.setContext(vars);

        // Execute this plugin
        plugin.run();

        Object o = plugin.get("sql");
        if (null != o && o instanceof Closure) {
            sql = ((Closure) o).call(msg).toString();
        } else if (o instanceof String || o instanceof GString) {
            sql = o.toString();
        } else {
            throw new IllegalStateException("Can't convert " + String.valueOf(o) + " to SQL statement.");
        }
        msg.setSql(sql);

        o = plugin.get("statementCreator");
        if (null != o && o instanceof Closure) {
            stmtCreator = new CallableStatementCreator() {
                public CallableStatement createCallableStatement(Connection con) throws SQLException {
                    Object obj = ((Closure) plugin.get("statementCreator")).call(new Object[] { con, msg });
                    log.debug("from plugin statementCreator: " + String.valueOf(obj));
                    return (CallableStatement) obj;
                }
            };
        } else {
            throw new IllegalStateException("Can't convert " + String.valueOf(o)
                    + " to CallableStatementCreator. Define a closure named 'statementCreator' in your plugin.");
        }

        o = plugin.get("callback");
        if (null != o && o instanceof Closure) {
            callback = new CallableStatementCallback<SqlMessage>() {
                public SqlMessage doInCallableStatement(CallableStatement cs)
                        throws SQLException, DataAccessException {
                    Object obj = ((Closure) plugin.get("callback")).call(new Object[] { cs, msg });
                    log.debug("from plugin callback: " + String.valueOf(obj));
                    return (SqlMessage) obj;
                }
            };
        } else {
            throw new IllegalStateException("Can't convert " + String.valueOf(o)
                    + " to CallableStatementCallback. Define a closure named 'callback' in your plugin.");
        }
    } else {
        stmtCreator = new CallableStatementCreator() {
            public CallableStatement createCallableStatement(Connection connection) throws SQLException {
                CallableStatement stmt = connection.prepareCall(msg.getSql());
                List<Object> params = msg.getParams();
                if (null != params) {
                    int index = 1;
                    for (Object obj : params) {
                        stmt.setObject(index++, obj);
                    }
                }
                return stmt;
            }
        };
        callback = new CallableStatementCallback<SqlMessage>() {
            public SqlMessage doInCallableStatement(CallableStatement callableStatement)
                    throws SQLException, DataAccessException {
                if (null == msg.getResults().getData()) {
                    msg.getResults().setData(new ArrayList<List<Object>>());
                }
                if (callableStatement.execute()) {
                    ResultSet results = callableStatement.getResultSet();

                    // Pull out column names
                    ResultSetMetaData meta = results.getMetaData();
                    String[] columns = new String[meta.getColumnCount()];
                    for (int i = 1; i <= meta.getColumnCount(); i++) {
                        columns[i - 1] = meta.getColumnName(i);
                    }
                    msg.getResults().getColumnNames().addAll(Arrays.asList(columns));

                    int total = 0;
                    while (results.next()) {
                        List<Object> row = new ArrayList<Object>(columns.length);
                        for (int i = 1; i <= columns.length; i++) {
                            row.add(results.getObject(i));
                        }
                        msg.getResults().getData().add(row);
                        total++;
                    }
                    msg.getResults().setTotalRows(total);

                } else {
                    msg.getResults().getColumnNames().add("updateCount");
                    msg.getResults().setTotalRows(1);
                    List<Object> updCnt = new ArrayList<Object>(1);
                    updCnt.add(callableStatement.getUpdateCount());
                    msg.getResults().getData().add(updCnt);
                }
                return msg;
            }
        };
    }
    try {
        tmpl.setExceptionTranslator(appCtx.getBean(SQLExceptionTranslator.class));
    } catch (NoSuchBeanDefinitionException notfound) {
        // IGNORED
    }

    if (null != stmtCreator && null != callback) {
        try {
            tmpl.execute(stmtCreator, callback);
        } catch (Throwable t) {
            log.error(t.getMessage(), t);
            List<String> errors = new ArrayList<String>();
            errors.add(t.getMessage());
            Throwable cause = t.getCause();
            if (null != cause) {
                do {
                    errors.add(cause.getMessage());
                } while (null != (cause = cause.getCause()));
            }
            msg.getResults().setErrors(errors);
        }
    } else {
        log.warn("CallableStatementCreator and/or CallableStatementCallback where empty. "
                + "Make sure your plugin provides these under 'statementCreator' and 'callback' respectively.");
    }
    return msg;
}

From source file:net.solarnetwork.node.dao.jdbc.derby.DerbyOnlineSyncJob.java

private void executeProcedure(final String procedure) {
    jdbcOperations.execute(new CallableStatementCreator() {
        public CallableStatement createCallableStatement(Connection con) throws SQLException {
            log.trace("Calling {} procedure", procedure);
            return con.prepareCall(procedure);
        }//from  w  w  w  .ja  v a  2 s  . com
    }, new CallableStatementCallback<Object>() {
        public Object doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
            cs.execute();
            return null;
        }
    });
}

From source file:org.kuali.coeus.common.impl.krms.StoredFunctionDao.java

public String executeFunction(final String functionName, final List<Object> paramValues) {

    final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

    String result = jdbcTemplate.execute(new CallableStatementCreator() {
        @Override/*from  www  . j av a 2  s .c o m*/
        public CallableStatement createCallableStatement(Connection con) throws SQLException {
            String paramSyntaxString = "";
            int paramCount = paramValues.size();
            for (int i = 0; i < paramCount; i++) {
                if (i == 0)
                    paramSyntaxString += "(?";
                else if (i == paramCount - 1)
                    paramSyntaxString += ",?)";
                else
                    paramSyntaxString += ",?";
            }
            if (paramCount == 1)
                paramSyntaxString += ")";
            CallableStatement cs = con.prepareCall("{ ? = call " + functionName + paramSyntaxString + "}");
            cs.registerOutParameter(1, Types.VARCHAR);
            for (int i = 0; i < paramValues.size(); i++) {
                cs.setObject(i + 2, paramValues.get(i));
            }
            return cs;
        }
    }, new CallableStatementCallback<String>() {
        @Override
        public String doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
            cs.execute();
            String result = cs.getString(1);
            return result;
        }

    });
    LOG.debug(functionName + " result: " + result);
    return result;
}

From source file:org.opoo.oqs.spring.SpringQuery.java

protected Object doCall() throws QueryException {
    final PreparedStatementSetter pss = new ArgTypePreparedStatementSetter(valueArray(), typeArray());
    final ResultSetExtractor rse = createResultSetExtractor(createListResultSetHandler());
    return jdbcTemplate.execute(getSql(), new CallableStatementCallback() {
        public Object doInCallableStatement(CallableStatement callableStatement)
                throws SQLException, DataAccessException {

            if (getQueryTimeout() > 0) {
                callableStatement.setQueryTimeout(getQueryTimeout());
            }// www.  j av a2  s .co m

            pss.setValues(callableStatement);

            boolean retVal = callableStatement.execute();
            int updateCount = callableStatement.getUpdateCount();
            if (log.isDebugEnabled()) {
                log.debug("CallableStatement.execute() returned '" + retVal + "'");
                log.debug("CallableStatement.getUpdateCount() returned " + updateCount);
            }

            ResultSet rs = callableStatement.getResultSet();
            try {
                if (rs != null && rse != null) {
                    return rse.extractData(rs);
                }
            } finally {
                JdbcUtils.closeResultSet(rs);
            }

            if (updateCount > 0) {
                return new Integer(updateCount);
            }
            return null;
        }
    });
}

From source file:org.springframework.jdbc.core.JdbcTemplate.java

public Map call(CallableStatementCreator csc, final List declaredParameters) throws DataAccessException {
    return (Map) execute(csc, new CallableStatementCallback() {
        public Object doInCallableStatement(CallableStatement cs) throws SQLException {
            boolean retVal = cs.execute();
            int updateCount = cs.getUpdateCount();
            if (logger.isDebugEnabled()) {
                logger.debug("CallableStatement.execute returned [" + retVal + "]");
                logger.debug("CallableStatement.getUpdateCount returned [" + updateCount + "]");
            }/*from   ww  w.j  a v a  2 s  .c om*/
            Map returnedResults = new HashMap();
            if (retVal || updateCount != -1) {
                returnedResults.putAll(extractReturnedResultSets(cs, declaredParameters, updateCount));
            }
            returnedResults.putAll(extractOutputParameters(cs, declaredParameters));
            return returnedResults;
        }
    });
}