Java Code Examples for org.springframework.jdbc.core.namedparam.MapSqlParameterSource

The following examples show how to use org.springframework.jdbc.core.namedparam.MapSqlParameterSource. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private List<LogCollection> getTransactionLogByIds(JdbcTemplate localJdbcTemplate, List<byte[]> transIdList) {
      List<DataBaseTransactionLogDetail> query;
      NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(localJdbcTemplate);
MapSqlParameterSource paramSource = new MapSqlParameterSource();
paramSource.addValue("ids", transIdList);
query = namedTemplate.query(selectTransDetailsByIds, paramSource,new BeanPropertyRowMapper<DataBaseTransactionLogDetail>(DataBaseTransactionLogDetail.class));
	

List<LogCollection> result = new ArrayList<LogCollection>();
List<DataBaseTransactionLogDetail> currentDoList = new ArrayList<DataBaseTransactionLogDetail>();
List<Content> currentContentList = new ArrayList<Content>();
byte[] currentId = null;
for(DataBaseTransactionLogDetail detailDo:query){
	if(!Arrays.equals(detailDo.getTransLogId(), currentId)){
		addToResult(result, currentDoList, currentContentList);
		currentContentList.clear();
		currentDoList.clear();
		currentId = detailDo.getTransLogId();
	}
	
	currentDoList.add(detailDo);
	currentContentList.addAll(deserializer(detailDo));
}
addToResult(result, currentDoList, currentContentList);
      return result;
  }
 
Example 2
public List<Statistic> createStatistic() {
	StringBuilder builder = new StringBuilder();
	builder.append("Select b.user_name, a.match_group, sum(b.points) ");
	builder.append("from matches a join bet b on a.match_id = b.match_id ");
	builder.append("where a.goals_team_one is not null  ");
	builder.append("and a.goals_team_two is not null  ");
	builder.append("and b.user_name not like :username ");
	builder.append("group by b.user_name, a.match_group;");

	MapSqlParameterSource params = new MapSqlParameterSource();
	params.addValue("username", FredbetConstants.TECHNICAL_USERNAME);

	final StatisticsCollector statisticsCollector = new StatisticsCollector();

	namedParameterJdbcOperations.query(builder.toString(), params, (ResultSet rs) -> {
		String userName = rs.getString(1);
		String group = rs.getString(2);
		int points = rs.getInt(3);
		statisticsCollector.addValue(userName, group, points);
	});

	return statisticsCollector.getResult();
}
 
Example 3
Source Project: alf.io   Source File: EventManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void rearrangeCategories(String eventName, List<CategoryOrdinalModification> categories, String username) {
    var optionalEvent = getOptionalEventAndOrganizationIdByName(eventName, username);
    if(optionalEvent.isPresent()) {
        int eventId = optionalEvent.get().getId();
        var parameterSources = categories.stream()
            .map(category -> new MapSqlParameterSource("ordinal", category.getOrdinal())
                .addValue("id", category.getId())
                .addValue("eventId", eventId))
            .toArray(MapSqlParameterSource[]::new);
        int[] results = jdbcTemplate.batchUpdate(ticketCategoryRepository.updateOrdinal(), parameterSources);
        Validate.isTrue(IntStream.of(results).sum() == categories.size(), "Unexpected result from update.");
    } else {
        log.warn("unauthorized access to event {}", eventName);
    }
}
 
Example 4
private MapSqlParameterSource buildParameterSource( Audit audit )
{
    MapSqlParameterSource parameters = new MapSqlParameterSource();

    parameters.addValue( "auditType", audit.getAuditType() );
    parameters.addValue( "auditScope", audit.getAuditScope() );
    parameters.addValue( "createdAt", audit.getCreatedAt() );
    parameters.addValue( "createdBy", audit.getCreatedBy() );
    parameters.addValue( "klass", audit.getKlass() );
    parameters.addValue( "uid", audit.getUid() );
    parameters.addValue( "code", audit.getCode() );
    parameters.addValue( "data", compress( audit.getData() ) );

    try
    {
        parameters.addValue( "attributes", jsonMapper.writeValueAsString( audit.getAttributes() ) );
    }
    catch ( JsonProcessingException ignored )
    {
    }

    return parameters;
}
 
Example 5
Source Project: piper   Source File: JdbcJobRepository.java    License: Apache License 2.0 6 votes vote down vote up
private MapSqlParameterSource createSqlParameterSource(Job aJob) {
  SimpleJob job = new SimpleJob(aJob);
  Assert.notNull(aJob, "job must not be null");
  Assert.notNull(aJob.getId(), "job status must not be null");
  Assert.notNull(aJob.getCreateTime(), "job createTime must not be null");
  Assert.notNull(aJob.getStatus(), "job status must not be null");
  MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource();
  sqlParameterSource.addValue("id", job.getId());
  sqlParameterSource.addValue("status", job.getStatus().toString());
  sqlParameterSource.addValue("currentTask", job.getCurrentTask());
  sqlParameterSource.addValue("pipelineId", job.getPipelineId());
  sqlParameterSource.addValue("label", job.getLabel());
  sqlParameterSource.addValue("createTime", job.getCreateTime());
  sqlParameterSource.addValue("startTime", job.getStartTime());
  sqlParameterSource.addValue("endTime", job.getEndTime());
  sqlParameterSource.addValue("priority", job.getPriority());
  sqlParameterSource.addValue("inputs", Json.serialize(json,job.getInputs()));
  sqlParameterSource.addValue("outputs", Json.serialize(json,job.getOutputs()));
  sqlParameterSource.addValue("webhooks", Json.serialize(json,job.getWebhooks()));
  sqlParameterSource.addValue("parentTaskExecutionId", job.getParentTaskExecutionId());
  return sqlParameterSource;
}
 
Example 6
@Override
public Set<String> findUserIdsConnectedTo(String providerId, Set<String> providerUserIds) {
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("providerId", providerId);
    parameters.addValue("providerUserIds", providerUserIds);
    final Set<String> localUserIds = new HashSet<String>();
    return new NamedParameterJdbcTemplate(jdbcTemplate).query("select userId from " + tablePrefix + "UserConnection where providerId = :providerId and providerUserId in (:providerUserIds)", parameters,
            new ResultSetExtractor<Set<String>>() {
                @Override
                public Set<String> extractData(ResultSet rs) throws SQLException, DataAccessException {
                    while (rs.next()) {
                        localUserIds.add(rs.getString("userId"));
                    }
                    return localUserIds;
                }
            });
}
 
Example 7
Source Project: effectivejava   Source File: SimpleJdbcCallTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddInvoiceProcWithoutMetaDataUsingMapParamSource() throws Exception {
	initializeAddInvoiceWithoutMetaData(false);
	SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withProcedureName("add_invoice");
	adder.declareParameters(
			new SqlParameter("amount", Types.INTEGER),
			new SqlParameter("custid", Types.INTEGER),
			new SqlOutParameter("newid",
			Types.INTEGER));
	Number newId = adder.executeObject(Number.class, new MapSqlParameterSource().
			addValue("amount", 1103).
			addValue("custid", 3));
	assertEquals(4, newId.intValue());
	verifyAddInvoiceWithoutMetaData(false);
	verify(connection, atLeastOnce()).close();
}
 
Example 8
Source Project: bistoury   Source File: ApplicationDaoImpl.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public List<Application> getApplicationsByAppCodes(List<String> appCodes) {
    if (CollectionUtils.isEmpty(appCodes)) {
        return Collections.emptyList();
    }
    final MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("code", appCodes);
    return namedParameterJdbcTemplate.query(SELECT_BY_APP_CODES, parameters, APPLICATIONS_MAPPER);
}
 
Example 9
Source Project: alf.io   Source File: TicketRepository.java    License: GNU General Public License v3.0 5 votes vote down vote up
default int[] batchReleaseTickets(String reservationId, List<Integer> ticketIds, Event event) {
    MapSqlParameterSource[] args = ticketIds.stream().map(id -> new MapSqlParameterSource("ticketId", id)
        .addValue("reservationId", reservationId)
        .addValue("eventId", event.getId())
        .addValue("newUuid", UUID.randomUUID().toString())
    ).toArray(MapSqlParameterSource[]::new);
    return getNamedParameterJdbcTemplate().batchUpdate(RELEASE_TICKET_QUERY, args);
}
 
Example 10
@Override
public Company findCompany(Integer pid) {
    logger.info("Finding Company by ID using JDBCTemplate");

    String query = "SELECT pid, address, name " +
            "FROM company " +
            "WHERE pid = :pid";

    MapSqlParameterSource params = new MapSqlParameterSource()
            .addValue("pid", pid);

    /*
     * Note that you can use BeanPropertyRowMapper instead (see findDepartment())
     */
    RowMapper<Company> mapper = (rs, rowNum) -> {
        Company row = new Company();
        row.setPid(rs.getInt("pid"));
        row.setAddress(rs.getString("address"));
        row.setName(rs.getString("name"));
        return row;
    };

    Company company = jdbcTemplate.queryForObject(query, params, mapper);

    logger.info("Found company: " + company);

    return company;
}
 
Example 11
@Test
public void testMatchParameterValuesAndSqlInOutParameters() throws Exception {
	final String TABLE = "customers";
	final String USER = "me";
	given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
	given(databaseMetaData.getUserName()).willReturn(USER);
	given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);

	List<SqlParameter> parameters = new ArrayList<SqlParameter>();
	parameters.add(new SqlParameter("id", Types.NUMERIC));
	parameters.add(new SqlInOutParameter("name", Types.NUMERIC));
	parameters.add(new SqlOutParameter("customer_no", Types.NUMERIC));

	MapSqlParameterSource parameterSource = new MapSqlParameterSource();
	parameterSource.addValue("id", 1);
	parameterSource.addValue("name", "Sven");
	parameterSource.addValue("customer_no", "12345XYZ");

	context.setProcedureName(TABLE);
	context.initializeMetaData(dataSource);
	context.processParameters(parameters);

	Map<String, Object> inParameters = context.matchInParameterValuesWithCallParameters(parameterSource);
	assertEquals("Wrong number of matched in parameter values", 2, inParameters.size());
	assertTrue("in parameter value missing", inParameters.containsKey("id"));
	assertTrue("in out parameter value missing", inParameters.containsKey("name"));
	assertTrue("out parameter value matched", !inParameters.containsKey("customer_no"));

	List<String> names = context.getOutParameterNames();
	assertEquals("Wrong number of out parameters", 2, names.size());

	List<SqlParameter> callParameters = context.getCallParameters();
	assertEquals("Wrong number of call parameters", 3, callParameters.size());
}
 
Example 12
Source Project: jeewx   Source File: GenericBaseCommonDao.java    License: Apache License 2.0 5 votes vote down vote up
public Object executeSqlReturnKey(final String sql, Map<String, Object> param) {
	Object keyValue = null;
	KeyHolder keyHolder = new GeneratedKeyHolder(); 
	SqlParameterSource sqlp  = new MapSqlParameterSource(param);
	this.namedParameterJdbcTemplate.update(sql,sqlp, keyHolder);
	if(oConvertUtils.isNotEmpty(keyHolder.getKey())){
		keyValue = keyHolder.getKey().longValue();
	}
	return keyValue;
}
 
Example 13
Source Project: alf.io   Source File: DataMigrator.java    License: GNU General Public License v3.0 5 votes vote down vote up
private List<Pair<String, MapSqlParameterSource>> collectASMigrationData(String srcPriceCtsParam, boolean eventVatIncluded, BigDecimal vatPercentage, Map<String, Integer> eventIdParam) {
    return jdbc.queryForList("select id, price_cts, vat_type from additional_service where event_id_fk = :eventId and fix_price = true and price_cts > 0 and src_price_cts = 0", eventIdParam)
        .stream()
        .map(as -> {
            int priceCts = (int) as.get("price_cts");
            AdditionalService.VatType vatType = AdditionalService.VatType.valueOf((String) as.get("vat_type"));
            int srcPrice = vatType == AdditionalService.VatType.INHERITED && eventVatIncluded ? MonetaryUtil.addVAT(priceCts, vatPercentage) : priceCts;
            return Pair.of("additional_service", new MapSqlParameterSource(srcPriceCtsParam, srcPrice).addValue("additionalServiceId", as.get("id")));
        }).collect(toList());
}
 
Example 14
Source Project: spring-boot   Source File: NamedParameterJdbcBookRepository.java    License: MIT License 5 votes vote down vote up
@Override
public Optional<Book> findById(Long id) {
    return namedParameterJdbcTemplate.queryForObject(
            "select * from books where id = :id",
            new MapSqlParameterSource("id", id),
            (rs, rowNum) ->
                    Optional.of(new Book(
                            rs.getLong("id"),
                            rs.getString("name"),
                            rs.getBigDecimal("price")
                    ))
    );
}
 
Example 15
Source Project: lams   Source File: SqlUpdate.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generic method to execute the update given named parameters.
 * All other update methods invoke this method.
 * @param paramMap Map of parameter name to parameter object,
 * matching named parameters specified in the SQL statement
 * @return the number of rows affected by the update
 */
public int updateByNamedParam(Map<String, ?> paramMap) throws DataAccessException {
	validateNamedParameters(paramMap);
	ParsedSql parsedSql = getParsedSql();
	MapSqlParameterSource paramSource = new MapSqlParameterSource(paramMap);
	String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource);
	Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, getDeclaredParameters());
	int rowsAffected = getJdbcTemplate().update(newPreparedStatementCreator(sqlToUse, params));
	checkRowsAffected(rowsAffected);
	return rowsAffected;
}
 
Example 16
public void insertResultNames(List<String> names){
    List<String> inDBNames = getResultNames();
    for(String name : names){
        if(inDBNames.contains(name)){
            continue;
        }
        MapSqlParameterSource parameters = new MapSqlParameterSource();
        parameters.addValue("name", name);
        this.template.update(INSERT_RESULT_NAMES, parameters);

    }
}
 
Example 17
/**
 * Creates a {@link MapSqlParameterSource} based on data values from the
 * supplied {@link Visit} instance.
 */
private MapSqlParameterSource createVisitParameterSource(Visit visit) {
	return new MapSqlParameterSource()
		.addValue("id", visit.getId())
		.addValue("visit_date", visit.getDate())
		.addValue("description", visit.getDescription())
		.addValue("pet_id", visit.getPet().getId());
}
 
Example 18
@Override
public int getExperimentState(int experimentTaskId) {
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("id", experimentTaskId);
    List<Integer> result = this.template.query(GET_TASK_STATE, parameters, new IntegerRowMapper());
    if (result.size() > 0) {
        return result.get(0);
    } else {
        return TASK_NOT_FOUND;
    }
}
 
Example 19
Source Project: alf.io   Source File: TicketRepository.java    License: GNU General Public License v3.0 5 votes vote down vote up
default void bulkTicketUpdate(List<Integer> ids, TicketCategory ticketCategory) {
    MapSqlParameterSource[] params = ids.stream().map(id -> new MapSqlParameterSource("id", id)
        .addValue("categoryId", ticketCategory.getId())
        .addValue("srcPriceCts", ticketCategory.getSrcPriceCts()))
        .toArray(MapSqlParameterSource[]::new);
    getNamedParameterJdbcTemplate().batchUpdate("update ticket set category_id = :categoryId, src_price_cts = :srcPriceCts where id = :id", params);
}
 
Example 20
@Transactional(readOnly = true)
public PagedResource<ProductSummaryRepresentation> listProducts(int pageIndex, int pageSize) {
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("limit", pageSize);
    parameters.addValue("offset", (pageIndex - 1) * pageSize);

    List<ProductSummaryRepresentation> products = jdbcTemplate.query(SELECT_SQL, parameters,
            (rs, rowNum) -> new ProductSummaryRepresentation(rs.getString("ID"),
                    rs.getString("NAME"),
                    rs.getBigDecimal("PRICE")));

    int total = jdbcTemplate.queryForObject(COUNT_SQL, newHashMap(), Integer.class);
    return PagedResource.of(total, pageIndex, products);
}
 
Example 21
Source Project: alf.io   Source File: GroupRepository.java    License: GNU General Public License v3.0 5 votes vote down vote up
default void deactivateGroupMember(List<Integer> memberIds, int groupId) {
    MapSqlParameterSource[] params = memberIds.stream().map(memberId ->
            new MapSqlParameterSource("groupId", groupId)
                .addValue("memberId", memberId)
                .addValue("disabledPlaceholder", UUID.randomUUID().toString())
        ).toArray(MapSqlParameterSource[]::new);
    getNamedParameterJdbcTemplate().batchUpdate("update group_member set active = false, value = 'DISABLED-' || :disabledPlaceholder where id = :memberId and a_group_id_fk = :groupId", params);
}
 
Example 22
Source Project: java-technology-stack   Source File: SqlUpdate.java    License: MIT License 5 votes vote down vote up
/**
 * Method to execute the update given arguments and
 * retrieve the generated keys using a KeyHolder.
 * @param paramMap a Map of parameter name to parameter object,
 * matching named parameters specified in the SQL statement
 * @param generatedKeyHolder the KeyHolder that will hold the generated keys
 * @return the number of rows affected by the update
 */
public int updateByNamedParam(Map<String, ?> paramMap, KeyHolder generatedKeyHolder) throws DataAccessException {
	validateNamedParameters(paramMap);
	ParsedSql parsedSql = getParsedSql();
	MapSqlParameterSource paramSource = new MapSqlParameterSource(paramMap);
	String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource);
	Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, getDeclaredParameters());
	int rowsAffected = getJdbcTemplate().update(newPreparedStatementCreator(sqlToUse, params), generatedKeyHolder);
	checkRowsAffected(rowsAffected);
	return rowsAffected;
}
 
Example 23
private MapSqlParameterSource createTaskParameters(String annotatorName, String datasetName, String experimentType,
        String matching) {
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("annotatorName", annotatorName);
    parameters.addValue("datasetName", datasetName);
    parameters.addValue("experimentType", experimentType);
    parameters.addValue("matching", matching);
    return parameters;
}
 
Example 24
Source Project: java-technology-stack   Source File: SimpleJdbcCallTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testAddInvoiceProcWithMetaDataUsingMapParamSource() throws Exception {
	initializeAddInvoiceWithMetaData(false);
	SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withProcedureName("add_invoice");
	Number newId = adder.executeObject(Number.class, new MapSqlParameterSource()
			.addValue("amount", 1103)
			.addValue("custid", 3));
	assertEquals(4, newId.intValue());
	verifyAddInvoiceWithMetaData(false);
	verify(connection, atLeastOnce()).close();
}
 
Example 25
Source Project: java-technology-stack   Source File: SimpleJdbcCallTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testAddInvoiceFuncWithoutMetaDataUsingMapParamSource() throws Exception {
	initializeAddInvoiceWithoutMetaData(true);
	SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withFunctionName("add_invoice");
	adder.declareParameters(
			new SqlOutParameter("return", Types.INTEGER),
			new SqlParameter("amount", Types.INTEGER),
			new SqlParameter("custid", Types.INTEGER));
	Number newId = adder.executeFunction(Number.class, new MapSqlParameterSource()
			.addValue("amount", 1103)
			.addValue("custid", 3));
	assertEquals(4, newId.intValue());
	verifyAddInvoiceWithoutMetaData(true);
	verify(connection, atLeastOnce()).close();
}
 
Example 26
Source Project: Microservices-with-Spring-Cloud   Source File: UserService.java    License: MIT License 5 votes vote down vote up
public void addUser(UserDetails userDetails) {
    jdbcTemplate.update("INSERT INTO users(username, password,enabled)" +
                    " VALUES (lower(:username),:password,1)",
            new MapSqlParameterSource("username", userDetails.getUsername())
                    .addValue("password", passwordEncoder.encode(userDetails.getPassword())));
    jdbcTemplate.batchUpdate("INSERT INTO authorities(username, authority) " +
                    "VALUES (lower(:username), :role)",
            (SqlParameterSource[]) userDetails.getAuthorities().stream()
                    .map(a -> new MapSqlParameterSource("username", userDetails.getUsername())
                            .addValue("role", a.getAuthority()))
                    .toArray(size -> new SqlParameterSource[size]));
}
 
Example 27
Source Project: spring-cloud-task   Source File: JdbcTaskExecutionDao.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public TaskExecution startTaskExecution(long executionId, String taskName,
		Date startTime, List<String> arguments, String externalExecutionId,
		Long parentExecutionId) {
	TaskExecution taskExecution = new TaskExecution(executionId, null, taskName,
			startTime, null, null, arguments, null, externalExecutionId,
			parentExecutionId);

	final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
			.addValue("startTime", startTime, Types.TIMESTAMP)
			.addValue("exitCode", null, Types.INTEGER)
			.addValue("taskName", taskName, Types.VARCHAR)
			.addValue("lastUpdated", new Date(), Types.TIMESTAMP)
			.addValue("parentExecutionId", parentExecutionId, Types.BIGINT)
			.addValue("taskExecutionId", executionId, Types.BIGINT);

	String updateString = START_TASK_EXECUTION_PREFIX;

	if (externalExecutionId == null) {
		updateString += START_TASK_EXECUTION_SUFFIX;
	}
	else {
		updateString += START_TASK_EXECUTION_EXTERNAL_ID_SUFFIX;
		queryParameters.addValue("externalExecutionId", externalExecutionId,
				Types.VARCHAR);
	}

	this.jdbcTemplate.update(getQuery(updateString), queryParameters);
	insertTaskArguments(executionId, arguments);
	return taskExecution;
}
 
Example 28
Source Project: java-technology-stack   Source File: TableMetaDataContextTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testTableWithSingleColumnGeneratedKey() throws Exception {
	final String TABLE = "customers";
	final String USER = "me";

	ResultSet metaDataResultSet = mock(ResultSet.class);
	given(metaDataResultSet.next()).willReturn(true, false);
	given(metaDataResultSet.getString("TABLE_SCHEM")).willReturn(USER);
	given(metaDataResultSet.getString("TABLE_NAME")).willReturn(TABLE);
	given(metaDataResultSet.getString("TABLE_TYPE")).willReturn("TABLE");

	ResultSet columnsResultSet = mock(ResultSet.class);
	given(columnsResultSet.next()).willReturn(true, false);
	given(columnsResultSet.getString("COLUMN_NAME")).willReturn("id");
	given(columnsResultSet.getInt("DATA_TYPE")).willReturn(Types.INTEGER);
	given(columnsResultSet.getBoolean("NULLABLE")).willReturn(false);

	given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
	given(databaseMetaData.getDatabaseProductName()).willReturn("1.0");
	given(databaseMetaData.getUserName()).willReturn(USER);
	given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
	given(databaseMetaData.getTables(null, null, TABLE, null)).willReturn(metaDataResultSet);
	given(databaseMetaData.getColumns(null, USER, TABLE, null)).willReturn(columnsResultSet);

	MapSqlParameterSource map = new MapSqlParameterSource();
	String[] keyCols = new String[] { "id" };
	context.setTableName(TABLE);
	context.processMetaData(dataSource, new ArrayList<>(), keyCols);
	List<Object> values = context.matchInParameterValuesWithInsertColumns(map);
	String insertString = context.createInsertString(keyCols);

	assertEquals("wrong number of parameters: ", 0, values.size());
	assertEquals("empty insert not generated correctly", "INSERT INTO customers () VALUES()", insertString);
	verify(metaDataResultSet, atLeastOnce()).next();
	verify(columnsResultSet, atLeastOnce()).next();
	verify(metaDataResultSet).close();
	verify(columnsResultSet).close();
}
 
Example 29
Source Project: qconfig   Source File: PropertiesEntryLogDaoImpl.java    License: MIT License 5 votes vote down vote up
@Override
public List<Long> selectLatestIdsOfDistinctKeys(Set<String> groups, String profile, String dataId, String key,
                                                String profileLike, String dataIdLike, String keyLike, int page, int pageSize) {
    if (CollectionUtils.isEmpty(groups)) {
        return ImmutableList.of();
    }
    KeyValuePair<StringBuilder, MapSqlParameterSource> sqlAndParams = genExtraQueryStringAndParams(groups, profile, dataId, key, profileLike, dataIdLike, keyLike);
    long offset = PaginationUtil.start(page, pageSize);
    String sql = sqlAndParams.getKey().toString();
    MapSqlParameterSource params = sqlAndParams.getValue();
    params.addValue("offset", offset);
    params.addValue("limit", pageSize);
    return namedParameterJdbcTemplate.query(String.format(SELECT_LATEST_IDS_OF_DISTINCT_KEYS, sql), params, ID_ROW_MAPPER);
}
 
Example 30
Source Project: qconfig   Source File: PropertiesEntryLogDaoImpl.java    License: MIT License 5 votes vote down vote up
@Override
public List<PropertiesEntryDiff> selectByIds(List<Long> ids) {
    if (CollectionUtils.isEmpty(ids)) {
        return ImmutableList.of();
    }
    MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue("ids", ids);
    return namedParameterJdbcTemplate.query(SELECT_BY_IDS, params, ENTRY_ROW_MAPPER);
}