@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); }
@Override public int update( String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder, String[] keyColumnNames) throws DataAccessException { ParsedSql parsedSql = getParsedSql(sql); String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource); Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, null); List<SqlParameter> declaredParameters = NamedParameterUtils.buildSqlParameterList(parsedSql, paramSource); PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory(sqlToUse, declaredParameters); if (keyColumnNames != null) { pscf.setGeneratedKeysColumnNames(keyColumnNames); } else { pscf.setReturnGeneratedKeys(true); } return getJdbcOperations().update(pscf.newPreparedStatementCreator(params), generatedKeyHolder); }
public int setTenantActive(TenantVO tenant, boolean active) { if (logger.isDebugEnabled()) { logger.debug("setting tenant '" + tenant.getStringId() + "' to " + active); } StringBuilder query = new StringBuilder("UPDATE "); query.append(DEFAULT_TABLE_NAME); query.append(" SET "); query.append(DEFAULT_ACTIVE_COLUMN_NAME).append("=?"); query.append(" WHERE "); query.append(DEFAULT_ID_COLUMN_NAME).append("=?"); Object[] args = {active, tenant.getId()}; int[] argTypes = {Types.BOOLEAN, Types.INTEGER}; PreparedStatementCreatorFactory factory = new PreparedStatementCreatorFactory(query.toString(), argTypes); return getJdbcTemplate().update(factory.newPreparedStatementCreator(args)); }
public int storeTenantConfig(Integer tenantId, String tenantConfig) { if (tenantId == null) { throw new IllegalArgumentException("tenantId must not be 'null'!"); } if (logger.isDebugEnabled()) { logger.debug("storing tenantConfig for tenant '" + tenantId + "'"); } StringBuilder query = new StringBuilder("UPDATE "); query.append(DEFAULT_TABLE_NAME); query.append(" SET "); query.append(DEFAULT_CONFIG_COLUMN_NAME).append("=?"); query.append(" WHERE "); query.append(DEFAULT_ID_COLUMN_NAME).append("=?"); Object[] args = {tenantConfig, tenantId}; int[] argTypes = {Types.VARCHAR, Types.INTEGER}; PreparedStatementCreatorFactory factory = new PreparedStatementCreatorFactory(query.toString(), argTypes); return getJdbcTemplate().update(factory.newPreparedStatementCreator(args)); }
public int storeTenantStatistic(Integer tenantId, String tenantStatistic) { if (tenantId == null) { throw new IllegalArgumentException("tenantId must not be 'null'!"); } if (logger.isDebugEnabled()) { logger.debug("storing tenantStatistic for tenant '" + tenantId + "'"); } StringBuilder query = new StringBuilder("UPDATE "); query.append(DEFAULT_TABLE_NAME); query.append(" SET "); query.append(DEFAULT_STATISTIC_COLUMN_NAME).append("=?"); query.append(" WHERE "); query.append(DEFAULT_ID_COLUMN_NAME).append("=?"); PreparedStatementCreatorFactory factory = new PreparedStatementCreatorFactory(query.toString(), new int[]{Types.VARCHAR, Types.INTEGER}); return getJdbcTemplate().update(factory.newPreparedStatementCreator(new Object[]{tenantStatistic, tenantId})); }
public int update( String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder, String[] keyColumnNames) throws DataAccessException { ParsedSql parsedSql = getParsedSql(sql); String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource); Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, null); List<SqlParameter> declaredParameters = NamedParameterUtils.buildSqlParameterList(parsedSql, paramSource); PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory(sqlToUse, declaredParameters); if (keyColumnNames != null) { pscf.setGeneratedKeysColumnNames(keyColumnNames); } else { pscf.setReturnGeneratedKeys(true); } return getJdbcOperations().update(pscf.newPreparedStatementCreator(params), generatedKeyHolder); }
public long insert(List<String> columns, List<Object> args, int[] types) { String insertColumns = primaryKeyName(); String insertPlaceholders = "nextval('"+tableName()+"_id_seq')"; for (String column : columns) { insertColumns += "," + column; insertPlaceholders += ",?"; } insertColumns += ", " + createdAtName(); insertPlaceholders += ", now()"; insertColumns += ", " + updatedAtName(); insertPlaceholders += ", now()"; String sql = "insert into " + tableName() + " ("+insertColumns+") values ("+insertPlaceholders+")"; KeyHolder keyHolder = new GeneratedKeyHolder(); PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory(sql, types); pscf.setReturnGeneratedKeys(true); try { logger.info("insert.sql: {}, args: {}", sql, jsonMapper.writeValueAsString(args)); } catch (JsonProcessingException e) { e.printStackTrace(); } writeJdbcTemplate.update(pscf.newPreparedStatementCreator(args), keyHolder); if (keyHolder.getKeyList() != null && !keyHolder.getKeyList().isEmpty()) { return (long) keyHolder.getKeyList().get(0).get(primaryKeyName()); } return -1; }
/** * Overridden method to configure the PreparedStatementCreatorFactory * based on our declared parameters. */ @Override protected final void compileInternal() { this.preparedStatementFactory = new PreparedStatementCreatorFactory(getSql(), getDeclaredParameters()); this.preparedStatementFactory.setResultSetType(getResultSetType()); this.preparedStatementFactory.setUpdatableResults(isUpdatableResults()); this.preparedStatementFactory.setReturnGeneratedKeys(isReturnGeneratedKeys()); if (getGeneratedKeysColumnNames() != null) { this.preparedStatementFactory.setGeneratedKeysColumnNames(getGeneratedKeysColumnNames()); } this.preparedStatementFactory.setNativeJdbcExtractor(getJdbcTemplate().getNativeJdbcExtractor()); onCompileInternal(); }
/** * Build a PreparedStatementCreator based on the given SQL and named parameters. * <p>Note: Not used for the {@code update} variant with generated key handling. * @param sql SQL to execute * @param paramSource container of arguments to bind * @return the corresponding PreparedStatementCreator */ protected PreparedStatementCreator getPreparedStatementCreator(String sql, SqlParameterSource paramSource) { ParsedSql parsedSql = getParsedSql(sql); String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource); Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, null); List<SqlParameter> declaredParameters = NamedParameterUtils.buildSqlParameterList(parsedSql, paramSource); PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory(sqlToUse, declaredParameters); return pscf.newPreparedStatementCreator(params); }
public void queryUnsafe(String input) { String sql = "select * from Users where name = '" + input + "' id=?"; new PreparedStatementCreatorFactory(sql); new PreparedStatementCreatorFactory(sql, new int[] {Types.INTEGER}); new PreparedStatementCreatorFactory(sql, new ArrayList<SqlParameter>()); }
protected PreparedStatementCreator getPreparedStatementCreator(String sql, SqlParameterSource paramSource) { ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql); String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource); Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, null); List<SqlParameter> declaredParameters = NamedParameterUtils.buildSqlParameterList(parsedSql, paramSource); PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory(sqlToUse, declaredParameters); return pscf.newPreparedStatementCreator(params); }
@Override public void setStudentAccount(Application application) { String sql = "INSERT INTO tblStudentUser (username, password) VALUES (?, ?)"; PreparedStatementCreatorFactory psCreateFactory = new PreparedStatementCreatorFactory(sql, new int[]{Types.VARCHAR, Types.VARCHAR}); jdbcTemplate.update(psCreateFactory.newPreparedStatementCreator(new Object[]{application.getUsername(),application.getPassword()})); }
protected PreparedStatementCreator getPreparedStatementCreator(String sql, Map<String,Object> paramMap) { MapSqlParameterSource paramSource = new MapSqlParameterSource(paramMap); ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql); String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource); Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, null); List<SqlParameter> declaredParameters = NamedParameterUtils.buildSqlParameterList(parsedSql, paramSource); PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory(sqlToUse, declaredParameters); pscf.setReturnGeneratedKeys(true); return pscf.newPreparedStatementCreator(params); }
/** * Cette méthode montre une autre façon d'utiliser un PreparedStatementSetter * Celui-ci est construit gréce à la classe PreparedStatementCreatorFactory */ public int updateNameWithPreparedStatementSetter(final String name, final int id) { String sqlUpdate = "update users set name = ? where id = ?"; PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory(sqlUpdate); // il faut préciser le type des variables pscf.addParameter(new SqlParameter(Types.NVARCHAR)); pscf.addParameter(new SqlParameter(Types.INTEGER)); // on récupére le PreparedStatementSetter PreparedStatementSetter pss = pscf.newPreparedStatementSetter(Arrays.asList(name, id)); // on lance l'update return jdbcTemplate.update(sqlUpdate, pss); }
/** * la méthode update peut servir à insérer des données * Dans le cas d'un insert avec increment automatique (sequence, autoincrement, on peut récupérer la clé générée) * Mais si on veut faire une insertion, on préfère le SimpleJdbcInsert */ public int insertNewUser(final int id, final String name, final String mail) { String sqlInsert = "insert into users (id, name, email) values (?, ?, ?)"; // on peut déclarer les types é l'initialisation de la factory PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory(sqlInsert, Types.INTEGER, Types.NVARCHAR, Types.NVARCHAR); PreparedStatementCreator psc = pscf.newPreparedStatementCreator(Arrays.asList(id, name, mail)); return jdbcTemplate.update(psc); }
public int insertTenant(TenantVO tenant) { if (logger.isDebugEnabled()) { logger.debug("inserting tenant '" + tenant.getStringId() + "'"); } StringBuilder query = new StringBuilder("INSERT INTO "); query.append(DEFAULT_TABLE_NAME); query.append(" SET "); query.append(DEFAULT_ID_COLUMN_NAME); query.append(" =?, "); query.append(DEFAULT_STRING_ID_COLUMN_NAME); query.append(" =?, "); query.append(DEFAULT_DESCRIPTION_COLUMN_NAME); query.append(" =?, "); query.append(DEFAULT_RATING_RANGE_MIN_COLUMN_NAME); query.append(" =?, "); query.append(DEFAULT_RATING_RANGE_MAX_COLUMN_NAME); query.append(" =?, "); query.append(DEFAULT_RATING_RANGE_NEUTRAL_COLUMN_NAME); query.append(" =?"); tenant.setId(getNewTenantId()); Object[] args = {tenant.getId(), tenant.getStringId(), tenant.getDescription(), tenant.getRatingRangeMin(), tenant.getRatingRangeMax(), tenant.getRatingRangeNeutral()}; int[] argTypes = {Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.INTEGER, Types.INTEGER, Types.DOUBLE}; PreparedStatementCreatorFactory factory = new PreparedStatementCreatorFactory(query.toString(), argTypes); getJdbcTemplate().update(factory.newPreparedStatementCreator(args)); return tenant.getId(); }
public int insertDomainURLForTenant(Integer tenantId, String domain) { if (tenantId == null) { throw new IllegalArgumentException("tenantId must not be 'null'!"); } if (domain == null) { throw new IllegalArgumentException("domain must not be 'null'!"); } if (domain.length() == 0) { throw new IllegalArgumentException("domain must not be an empty String!"); } StringBuilder sqlString = new StringBuilder("INSERT INTO "); sqlString.append(DEFAULT_TABLE_NAME); sqlString.append(" SET "); sqlString.append(DEFAULT_TENANT_ID_COLUMN_NAME); sqlString.append(" =?, "); sqlString.append(DEFAULT_DOMAIN_URL_COLUMN_NAME); sqlString.append("=?"); Object[] args = {tenantId, domain}; int[] argTypes = {Types.INTEGER, Types.VARCHAR}; PreparedStatementCreatorFactory factory = new PreparedStatementCreatorFactory(sqlString.toString(), argTypes); int rowsAffected = getJdbcTemplate().update(factory.newPreparedStatementCreator(args)); return rowsAffected; }
public int storeProfile(Integer tenantId, Integer itemId, Integer itemTypeId, String profileXML) { if (tenantId == null) { throw new IllegalArgumentException("tenantId must not be 'null'!"); } if (itemId == null) { throw new IllegalArgumentException("itemId must not be 'null'!"); } if (itemTypeId == null) { throw new IllegalArgumentException("itemTypeId must not be 'null'"); } String itemType = itemTypeDAO.getTypeById(tenantId, itemTypeId); String mappedItemId = idMappingDAO.lookup(itemId); if (mappedItemId == null) throw new IllegalArgumentException("itemId has no string equivalent"); Object[] args = {tenantId, mappedItemId, itemType, profileXML, profileXML}; int[] argTypes = {Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.BLOB, Types.BLOB}; PreparedStatementCreatorFactory factory = new PreparedStatementCreatorFactory(STORE_PROFILE_QUERY, argTypes); int rowsAffected = getJdbcTemplate().update(factory.newPreparedStatementCreator(args)); return rowsAffected; }
@Override public boolean deleteProfile(Integer tenantId, Integer itemId, Integer itemTypeId) { if (tenantId == null) { throw new IllegalArgumentException("tenantId must not be 'null'!"); } if (itemId == null) { throw new IllegalArgumentException("itemId must not be 'null'!"); } if (itemTypeId == null) { throw new IllegalArgumentException("itemTypeId must not be 'null'"); } String itemType = itemTypeDAO.getTypeById(tenantId, itemTypeId); String mappedItemId = idMappingDAO.lookup(itemId); if (mappedItemId == null) throw new IllegalArgumentException("itemId has no string equivalent"); Object[] args = {tenantId, mappedItemId, itemType, null, null}; int[] argTypes = {Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.BLOB, Types.BLOB}; PreparedStatementCreatorFactory factory = new PreparedStatementCreatorFactory(STORE_PROFILE_QUERY, argTypes); int rowsAffected = getJdbcTemplate().update(factory.newPreparedStatementCreator(args)); return (rowsAffected > 0); }
protected void processStreamList(Exchange exchange, String sql, SqlParameterSource param) throws Exception { // spring JDBC to parse the SQL and build the prepared statement creator // this is what NamedJdbcTemplate does internally ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql); String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, param); Object[] params = NamedParameterUtils.buildValueArray(parsedSql, param, null); List<SqlParameter> declaredParameters = NamedParameterUtils.buildSqlParameterList(parsedSql, param); PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory(sqlToUse, declaredParameters); PreparedStatementCreator statementCreator = pscf.newPreparedStatementCreator(params); processStreamList(exchange, statementCreator, sqlToUse); }
public long insert(Document message) { logger.debug("Inserting message by SQL"); String insertQuery = "INSERT INTO t5_message ( time, content ) VALUES ( ?, XMLPARSE( DOCUMENT ? ))"; String xmlContent; try { xmlContent = T5FHIRUtils.xmlToString(message); } catch (UnsupportedEncodingException | TransformerException e) { throw new T5Exception("Error deserializing message", e); } PreparedStatementCreatorFactory pscFactory = new PreparedStatementCreatorFactory(insertQuery, Types.TIMESTAMP, Types.VARCHAR); pscFactory.setReturnGeneratedKeys(true); pscFactory.setGeneratedKeysColumnNames("id"); PreparedStatementCreator psc = pscFactory .newPreparedStatementCreator(Arrays.asList(new Date(), xmlContent)); logger.debug("Writing message to db: " + xmlContent); KeyHolder messageKeyHolder = new GeneratedKeyHolder(); if (jdbcTemplate.update(psc, messageKeyHolder) != 1) { throw new DatabaseException("Message insertion failed."); } return messageKeyHolder.getKey().longValue(); }
public boolean deleteProfile(Integer tenantId, Integer itemId, Integer itemTypeId) { if (tenantId == null) { throw new IllegalArgumentException("tenantId must not be 'null'!"); } if (itemId == null) { throw new IllegalArgumentException("itemId must not be 'null'!"); } if (itemTypeId == null) { throw new IllegalArgumentException("itemTypeId must not be 'null'"); } String itemType = itemTypeDAO.getTypeById(tenantId, itemTypeId); String mappedItemId = idMappingDAO.lookup(itemId); if (mappedItemId == null) throw new IllegalArgumentException("itemId has no string equivalent"); Object[] args = {tenantId, mappedItemId, itemType, null, null}; int[] argTypes = {Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.BLOB, Types.BLOB}; PreparedStatementCreatorFactory factory = new PreparedStatementCreatorFactory(STORE_PROFILE_QUERY, argTypes); int rowsAffected = getJdbcTemplate().update(factory.newPreparedStatementCreator(args)); return (rowsAffected > 0); }