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

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

Introduction

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

Prototype

PreparedStatementCallback

Source Link

Usage

From source file:hr.fer.zemris.vhdllab.dao.impl.ProjectDaoImplTest.java

private void setupProject(final Project project) {
    String query = createInsertStatement("projects", "id, version, name, user_id", "null, 0, ?, ?");
    getJdbcTemplate().execute(query, new PreparedStatementCallback() {
        @Override/*from  w  ww . ja v  a 2  s  .  c  om*/
        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ps.setString(1, project.getName());
            ps.setString(2, project.getUserId());
            return ps.execute();
        }
    });
}

From source file:net.solarnetwork.node.dao.jdbc.reactor.JdbcInstructionDao.java

@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public Long storeInstruction(final Instruction instruction) {
    // first store our Instruction entity
    final Long pk = storeDomainObject(instruction, getSqlResource(RESOURCE_SQL_INSERT_INSTRUCTION));

    // now store all the Instruction's parameters
    getJdbcTemplate().execute(new PreparedStatementCreator() {

        @Override/*from   w  w w.  j a  va  2 s.co m*/
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement ps = con.prepareStatement(getSqlResource(RESOURCE_SQL_INSERT_INSTRUCTION_PARAM));
            return ps;
        }
    }, new PreparedStatementCallback<Object>() {

        @Override
        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            int pos = 0;
            for (String paramName : instruction.getParameterNames()) {
                String[] paramValues = instruction.getAllParameterValues(paramName);
                if (paramValues == null || paramValues.length < 1) {
                    continue;
                }
                for (String paramValue : paramValues) {
                    int col = 1;
                    ps.setLong(col++, pk);
                    ps.setLong(col++, pos);
                    ps.setString(col++, paramName);
                    ps.setString(col++, paramValue);
                    ps.addBatch();
                    pos++;
                }
            }
            int[] batchResults = ps.executeBatch();
            if (log.isTraceEnabled()) {
                log.trace("Batch inserted {} instruction params: {}", pos, Arrays.toString(batchResults));
            }
            return null;
        }
    });

    // finally crate a status row
    Date statusDate = new Date();
    getJdbcTemplate().update(getSqlResource(RESOURCE_SQL_INSERT_INSTRUCTION_STATUS), pk,
            new java.sql.Timestamp(statusDate.getTime()), InstructionState.Received.toString());
    return pk;
}

From source file:net.solarnetwork.node.dao.jdbc.AbstractJdbcDao.java

/**
 * Persist a domain object, without using auto-generated keys.
 * /*from   w  w w. j  av a  2 s  .c  o m*/
 * @param obj
 *        the domain object to persist
 * @param sqlInsert
 *        the SQL insert statement to use
 * @return the primary key created for the domain object
 */
protected Long storeDomainObjectWithoutAutogeneratedKeys(final T obj, final String sqlInsert) {
    Object result = getJdbcTemplate().execute(new PreparedStatementCreator() {

        @Override
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement ps = con.prepareStatement(sqlInsert);
            setStoreStatementValues(obj, ps);
            return ps;
        }
    }, new PreparedStatementCallback<Object>() {

        @Override
        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ps.execute();
            int count = ps.getUpdateCount();
            if (count == 1 && ps.getMoreResults()) {
                ResultSet rs = ps.getResultSet();
                if (rs.next()) {
                    return rs.getObject(1);
                }
            }
            return null;
        }
    });
    if (result instanceof Long) {
        return (Long) result;
    } else if (result instanceof Number) {
        return Long.valueOf(((Number) result).longValue());
    }
    if (log.isWarnEnabled()) {
        log.warn("Unexpected (non-number) primary key returned: " + result);
    }
    return null;
}

From source file:com.yahoo.sql4d.indexeragent.sql.DBAccessor.java

/**
 * Suitable for CRUD operations where no result set is expected.
 * @param params/*  w w  w .  ja  v  a 2  s .c  om*/
 * @param query 
 * @return  
 */
public boolean execute(Map<String, String> params, String query) {
    final AtomicBoolean result = new AtomicBoolean(false);
    Tuple2<DataSource, Connection> conn = null;
    try {
        conn = getConnection();
        NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(conn._1());
        jdbcTemplate.execute(query, params, new PreparedStatementCallback<Void>() {
            @Override
            public Void doInPreparedStatement(PreparedStatement ps) {
                try {
                    result.set(ps.execute());
                } catch (SQLException e) {
                    result.set(false);
                }
                return null;
            }
        });
    } catch (Exception ex) {
        Logger.getLogger(DBAccessor.class.getName()).log(Level.SEVERE, null, ex);
        result.set(false);
    } finally {
        returnConnection(conn);
    }
    return result.get();
}

From source file:ru.org.linux.comment.CommentDaoImpl.java

@Override
public int saveNewMessage(final Comment comment, String message) {
    final int msgid = jdbcTemplate.queryForInt("select nextval('s_msgid') as msgid");

    jdbcTemplate.execute(//from ww w.java2  s.com
            "INSERT INTO comments (id, userid, title, postdate, replyto, deleted, topic, postip, ua_id) VALUES (?, ?, ?, CURRENT_TIMESTAMP, ?, 'f', ?, ?::inet, create_user_agent(?))",
            new PreparedStatementCallback<Object>() {
                @Override
                public Object doInPreparedStatement(PreparedStatement pst)
                        throws SQLException, DataAccessException {
                    pst.setInt(1, msgid);
                    pst.setInt(2, comment.getUserid());
                    pst.setString(3, comment.getTitle());
                    pst.setInt(5, comment.getTopicId());
                    pst.setString(6, comment.getPostIP());
                    pst.setString(7, comment.getUserAgent());

                    if (comment.getReplyTo() != 0) {
                        pst.setInt(4, comment.getReplyTo());
                    } else {
                        pst.setNull(4, Types.INTEGER);
                    }

                    pst.executeUpdate();

                    return null;
                }
            });

    insertMsgbase.execute(ImmutableMap.<String, Object>of("id", msgid, "message", message, "bbcode", true));

    return msgid;
}

From source file:org.aksw.gerbil.database.ExperimentDAOImpl.java

@Override
public void close() throws IOException {
    this.template.execute(SHUTDOWN, new PreparedStatementCallback<Object>() {
        @Override/*from   w w  w. j a v a2 s .  co m*/
        public Object doInPreparedStatement(PreparedStatement arg0) throws SQLException, DataAccessException {
            // nothing to do
            return null;
        }
    });
}

From source file:cc.tooyoung.common.db.JdbcTemplate.java

/**
 * Query using a prepared statement, allowing for a PreparedStatementCreator
 * and a PreparedStatementSetter. Most other query methods use this method,
 * but application code will always work with either a creator or a setter.
 * @param psc Callback handler that can create a PreparedStatement given a
 * Connection//from w ww.  ja va  2  s .  c  o m
 * @param pss object that knows how to set values on the prepared statement.
 * If this is null, the SQL will be assumed to contain no bind parameters.
 * @param rse object that will extract results.
 * @return an arbitrary result object, as returned by the ResultSetExtractor
 * @throws DataAccessException if there is any problem
 */
public Object query(PreparedStatementCreator psc, final PreparedStatementSetter pss,
        final ResultSetExtractor rse) throws DataAccessException {

    Assert.notNull(rse, "ResultSetExtractor must not be null");
    if (ApiLogger.isTraceEnabled())
        ApiLogger.trace("Executing prepared SQL query");

    return execute(psc, new PreparedStatementCallback() {
        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
            ResultSet rs = null;
            try {
                if (pss != null) {
                    pss.setValues(ps);
                }
                rs = ps.executeQuery();
                ResultSet rsToUse = rs;
                if (nativeJdbcExtractor != null) {
                    rsToUse = nativeJdbcExtractor.getNativeResultSet(rs);
                }
                return rse.extractData(rsToUse);
            } finally {
                JdbcUtils.closeResultSet(rs);
                if (pss instanceof ParameterDisposer) {
                    ((ParameterDisposer) pss).cleanupParameters();
                }
            }
        }
    }, false);
}

From source file:cc.tooyoung.common.db.JdbcTemplate.java

protected int update(final PreparedStatementCreator psc, final PreparedStatementSetter pss)
        throws DataAccessException {

    if (ApiLogger.isTraceEnabled()) {
        ApiLogger.trace("Executing prepared SQL update");
    }//  w w  w .j  a va 2  s  .co m

    Integer result = (Integer) execute(psc, new PreparedStatementCallback() {
        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
            try {
                if (pss != null) {
                    pss.setValues(ps);
                }
                int rows = ps.executeUpdate();
                if (ApiLogger.isTraceEnabled()) {
                    ApiLogger.trace("SQL update affected " + rows + " rows");
                }
                return new Integer(rows);
            } finally {
                if (pss instanceof ParameterDisposer) {
                    ((ParameterDisposer) pss).cleanupParameters();
                }
            }
        }
    }, true);
    return result.intValue();
}

From source file:cc.tooyoung.common.db.JdbcTemplate.java

@SuppressWarnings("unchecked")
public int update(final PreparedStatementCreator psc, final KeyHolder generatedKeyHolder)
        throws DataAccessException {

    Assert.notNull(generatedKeyHolder, "KeyHolder must not be null");
    if (ApiLogger.isTraceEnabled()) {
        ApiLogger.trace("Executing SQL update and returning generated keys");
    }/*from  w  ww. j a v a 2 s.  c  o  m*/

    Integer result = (Integer) execute(psc, new PreparedStatementCallback() {
        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
            int rows = ps.executeUpdate();
            List generatedKeys = generatedKeyHolder.getKeyList();
            generatedKeys.clear();
            ResultSet keys = ps.getGeneratedKeys();
            if (keys != null) {
                try {
                    RowMapper rowMapper = getColumnMapRowMapper();
                    RowMapperResultSetExtractor rse = new RowMapperResultSetExtractor(rowMapper, 1);
                    generatedKeys.addAll((List) rse.extractData(keys));
                } finally {
                    JdbcUtils.closeResultSet(keys);
                }
            }
            if (ApiLogger.isTraceEnabled()) {
                ApiLogger.trace(
                        "SQL update affected " + rows + " rows and returned " + generatedKeys.size() + " keys");
            }
            return new Integer(rows);
        }
    }, true);
    return result.intValue();
}