org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource#org.springframework.jdbc.core.namedparam.SqlParameterSource源码实例Demo

下面列出了org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource#org.springframework.jdbc.core.namedparam.SqlParameterSource 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: FastSQL   文件: BaseDAO.java
/**
 * 批量插入
 */
public int[] batchInsert(List<E> entities) {

    StringBuilder nameBuilder = new StringBuilder();
    StringBuilder valueBuilder = new StringBuilder();
    fields.forEach(field -> {
        nameBuilder.append(",").append(StringExtUtils.camelToUnderline(field.getName()));
        valueBuilder.append(",:").append(field.getName());
    });


    String sql = getSQL()
            .INSERT_INTO(tableName, nameBuilder.deleteCharAt(0).toString())
            .VALUES(valueBuilder.deleteCharAt(0).toString()).build();

    SqlParameterSource[] sqlParameterSources = new BeanPropertySqlParameterSource[entities.size()];
    for (int i = 0; i < sqlParameterSources.length; i++) {
        sqlParameterSources[i] = new BeanPropertySqlParameterSource(entities.get(i));
    }

    return getSQL().getNamedParameterJdbcTemplate().batchUpdate(sql, sqlParameterSources);
}
 
源代码2 项目: SimpleFlatMapper   文件: SqlParameterSourceTest.java
@Test
public void testIssue589() {
    SqlParameterSourceFactory<Issue589> parameterSourceFactory = JdbcTemplateMapperFactory.newInstance()
            .ignorePropertyNotFound()
            .addAlias("timestamp_", "timestamp")
            .addColumnProperty("timestamp_", SqlTypeColumnProperty.of(Types.TIMESTAMP))
            .newSqlParameterSourceFactory(Issue589.class);
    
    ZonedDateTime now = ZonedDateTime.now();
    Issue589 issue589 = new Issue589(now);

    SqlParameterSource sqlParameterSource = parameterSourceFactory.newSqlParameterSource(issue589);
    
    assertEquals(Types.TIMESTAMP, sqlParameterSource.getSqlType("timestamp_"));
    assertEquals(new Timestamp(Date.from(now.toInstant()).getTime()), sqlParameterSource.getValue("timestamp_"));
}
 
源代码3 项目: piper   文件: JdbcTaskExecutionRepository.java
private SqlParameterSource createSqlParameterSource (TaskExecution aTaskExecution) {
  MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource();
  sqlParameterSource.addValue("id", aTaskExecution.getId());
  sqlParameterSource.addValue("parentId", aTaskExecution.getParentId());
  sqlParameterSource.addValue("jobId", aTaskExecution.getJobId());
  sqlParameterSource.addValue("status", aTaskExecution.getStatus().toString());
  sqlParameterSource.addValue("progress", aTaskExecution.getProgress());
  sqlParameterSource.addValue("createTime", aTaskExecution.getCreateTime());
  sqlParameterSource.addValue("startTime", aTaskExecution.getStartTime());
  sqlParameterSource.addValue("endTime", aTaskExecution.getEndTime());
  sqlParameterSource.addValue("serializedExecution", Json.serialize(json, aTaskExecution));
  sqlParameterSource.addValue("priority", aTaskExecution.getPriority());
  sqlParameterSource.addValue("taskNumber", aTaskExecution.getTaskNumber());
  return sqlParameterSource;
}
 
源代码4 项目: SimpleFlatMapper   文件: Issue625Test.java
@Test
public void testSourceFactory() {
    String query = "WITH some_cte AS (\n" +
            "    SELECT :form_email_address\n" +
            "    FROM something s\n" +
            ")\n" +
            "SELECT :form_name\n" +
            "FROM something s";
    SqlParameterSourceFactory<Issue625> sourceFactory = JdbcTemplateMapperFactory.newInstance().newSqlParameterSourceFactory(Issue625.class, query);

    SqlParameterSource sqlParameterSource = sourceFactory.newSqlParameterSource(new Issue625("email", "value"));

    assertEquals("email", sqlParameterSource.getValue("form_email_address"));
    assertEquals("value", sqlParameterSource.getValue("form_name"));
}
 
源代码5 项目: maven-framework-project   文件: JdbcCustomerDAO.java
/**
 * 使用SimpleJdbcInsert和BeanPropertySqlParameterSource方式 新增数据
 * @param customer
 */
public void useBeanPropertySqlParameterSource(Customer customer){
	//封装BeanPropertySqlParameterSource
	SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(customer);
	//设置表名(withTableName)和设置自增长主键(usingGeneratedKeyColumns)
	Number key = simpleJdbcInsert.withTableName("CUSTOMER").usingGeneratedKeyColumns("CUST_ID").executeAndReturnKey(parameterSource);
	customer.setCustId(key.intValue());//返回新增后的主键
	System.out.println(customer.getCustId());
}
 
源代码6 项目: SimpleFlatMapper   文件: SqlParameterSourceTest.java
@Test
public void testConstantValue() {
    SqlParameterSourceFactory<DbObject> parameterSourceFactory =
            JdbcTemplateMapperFactory
                    .newInstance()
                    .addColumnProperty("id", new ConstantValueProperty<Long>(-3l, Long.class))
                    .newSqlParameterSourceFactory(DbObject.class);

    SqlParameterSource parameterSource = parameterSourceFactory.newSqlParameterSource(new DbObject());

    assertEquals(-3l, parameterSource.getValue("id"));

}
 
public SqlParameterSource[] newSqlParameterSources(Iterator<T> values) {
    ArrayList<SqlParameterSource> sources = new ArrayList<SqlParameterSource>();
    while(values.hasNext()) {
        sources.add(newSqlParameterSource(values.next()));
    }
    return sources.toArray(new SqlParameterSource[0]);
}
 
源代码8 项目: jeecg   文件: MigrateForm.java
public static SqlParameterSource generateParameterMap(Object t, List<String> ignores){
	Map<String, Object> paramMap = new HashMap<String, Object>();
	ReflectHelper reflectHelper = new ReflectHelper(t);
	PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(t.getClass());
	for (PropertyDescriptor pd : pds) {
		if(null != ignores && ignores.contains(pd.getName())){
			continue;
		}
		paramMap.put(pd.getName(), reflectHelper.getMethodValue(pd.getName()));
	}
	MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource(paramMap);
	return sqlParameterSource;
}
 
源代码9 项目: quartz-glass   文件: JdbcJobExecutions.java
@Override
public Page<JobExecution> find(String jobGroup, String jobName, Query query) {
    String sql = "from " + getTableName() + " where jobGroup = :jobGroup and jobName = :jobName";

    SqlParameterSource source = new MapSqlParameterSource()
            .addValue("jobGroup", jobGroup)
            .addValue("jobName", jobName);

    return getLogs(sql, source, query);
}
 
源代码10 项目: jeewx   文件: MigrateForm.java
public static SqlParameterSource generateParameterMap(Object t, List<String> ignores){
	Map<String, Object> paramMap = new HashMap<String, Object>();
	ReflectHelper reflectHelper = new ReflectHelper(t);
	PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(t.getClass());
	for (PropertyDescriptor pd : pds) {
		if(null != ignores && ignores.contains(pd.getName())){
			continue;
		}
		paramMap.put(pd.getName(), reflectHelper.getMethodValue(pd.getName()));
	}
	MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource(paramMap);
	return sqlParameterSource;
}
 
源代码11 项目: effectivejava   文件: TableMetaDataContext.java
/**
 * Match the provided column names and values with the list of columns used.
 * @param parameterSource the parameter names and values
 */
public List<Object> matchInParameterValuesWithInsertColumns(SqlParameterSource parameterSource) {
	List<Object> values = new ArrayList<Object>();
	// for parameter source lookups we need to provide caseinsensitive lookup support since the
	// database metadata is not necessarily providing case sensitive column names
	Map<String, String> caseInsensitiveParameterNames =
			SqlParameterSourceUtils.extractCaseInsensitiveParameterNames(parameterSource);
	for (String column : this.tableColumns) {
		if (parameterSource.hasValue(column)) {
			values.add(SqlParameterSourceUtils.getTypedValue(parameterSource, column));
		}
		else {
			String lowerCaseName = column.toLowerCase();
			if (parameterSource.hasValue(lowerCaseName)) {
				values.add(SqlParameterSourceUtils.getTypedValue(parameterSource, lowerCaseName));
			}
			else {
				String propertyName = JdbcUtils.convertUnderscoreNameToPropertyName(column);
				if (parameterSource.hasValue(propertyName)) {
					values.add(SqlParameterSourceUtils.getTypedValue(parameterSource, propertyName));
				}
				else {
					if (caseInsensitiveParameterNames.containsKey(lowerCaseName)) {
						values.add(
								SqlParameterSourceUtils.getTypedValue(parameterSource,
										caseInsensitiveParameterNames.get(lowerCaseName)));
					}
					else {
						values.add(null);
					}
				}
			}
		}
	}
	return values;
}
 
源代码12 项目: effectivejava   文件: AbstractJdbcInsert.java
/**
 * Method that provides execution of a batch insert using the passed in array of {@link SqlParameterSource}
 * @param batch array of SqlParameterSource with parameter names and values to be used in insert
 * @return array of number of rows affected
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
protected int[] doExecuteBatch(SqlParameterSource[] batch) {
	checkCompiled();
	List[] batchValues = new ArrayList[batch.length];
	int i = 0;
	for (SqlParameterSource parameterSource : batch) {
		List<Object> values = matchInParameterValuesWithInsertColumns(parameterSource);
		batchValues[i++] = values;
	}
	return executeBatchInternal(batchValues);
}
 
源代码13 项目: ureport   文件: DatasourceServletAction.java
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);
}
 
源代码14 项目: maestro-java   文件: EasyRunner.java
/**
 * Inserts a record in the DB
 * @param jdbcTemplate the Spring JDBC template object
 * @param query the query to run
 * @param bean the bean with the data to insert
 * @return the ID of the record updated
 */
public static int runInsert(final NamedParameterJdbcTemplate jdbcTemplate, final String query, final Object bean) {
    SqlParameterSource beanParameters = new BeanPropertySqlParameterSource(bean);
    KeyHolder keyHolder = new GeneratedKeyHolder();

    jdbcTemplate.update(query, beanParameters, keyHolder);
    return keyHolder.getKey().intValue();
}
 
public SqlParameterSource[] newSqlParameterSources(T[] values) {
    SqlParameterSource[] sources = new SqlParameterSource[values.length];

    for(int i = 0; i < values.length; i++) {
        T value = values[i];
        sources[i] = newSqlParameterSource(value);
    }
    return sources;
}
 
源代码16 项目: maven-framework-project   文件: JdbcCustomerDAO.java
/**
 * 使用SimpleJdbcInsert和MapSqlParameterSource方式 新增数据
 * @param customer
 */
public void useMapSqlParameterSource(Customer customer){
	//封装MapSqlParameterSource
	SqlParameterSource parameterSource = new MapSqlParameterSource().
			addValue("NAME", customer.getName()).//为NAME列填充值
			addValue("AGE", customer.getAge());//为AGE列填充值
	//设置表名(withTableName)和设置自增长主键(usingGeneratedKeyColumns)
	Number key = simpleJdbcInsert.withTableName("CUSTOMER").usingGeneratedKeyColumns("CUST_ID").executeAndReturnKey(parameterSource);
	customer.setCustId(key.intValue());//返回新增后的主键
	System.out.println(customer.getCustId());
}
 
源代码17 项目: effectivejava   文件: SimpleJdbcTemplate.java
@Override
public int[] batchUpdate(String sql, SqlParameterSource[] batchArgs) {
	return getNamedParameterJdbcOperations().batchUpdate(sql, batchArgs);
}
 
源代码18 项目: spring-analysis-note   文件: AbstractJdbcInsert.java
/**
 * Delegate method that executes the insert using the passed-in {@link SqlParameterSource}.
 * @param parameterSource parameter names and values to be used in insert
 * @return the number of rows affected
 */
protected int doExecute(SqlParameterSource parameterSource) {
	checkCompiled();
	List<Object> values = matchInParameterValuesWithInsertColumns(parameterSource);
	return executeInsertInternal(values);
}
 
源代码19 项目: effectivejava   文件: SimpleJdbcTemplate.java
@Override
public <T> T queryForObject(String sql, RowMapper<T> rm, SqlParameterSource args)
		throws DataAccessException {
	return getNamedParameterJdbcOperations().queryForObject(sql, args, rm);
}
 
源代码20 项目: alf.io   文件: UploadedResourceRepository.java
default void fileContent(int organizationId, String name, OutputStream out) {
    SqlParameterSource param = new MapSqlParameterSource("name", name).addValue("organizationId", organizationId);
    getNamedParameterJdbcTemplate().query("select content from resource_organizer where name = :name and organization_id_fk = :organizationId", param, OUTPUT_CONTENT.apply(out));
}
 
源代码21 项目: effectivejava   文件: SimpleJdbcCall.java
@Override
@SuppressWarnings("unchecked")
public <T> T executeFunction(Class<T> returnType, SqlParameterSource args) {
	return (T) doExecute(args).get(getScalarOutParameterName());
}
 
源代码22 项目: spring-analysis-note   文件: SimpleJdbcInsert.java
@Override
public Number executeAndReturnKey(SqlParameterSource parameterSource) {
	return doExecuteAndReturnKey(parameterSource);
}
 
源代码23 项目: effectivejava   文件: SimpleJdbcInsert.java
@Override
public int execute(SqlParameterSource parameterSource) {
	return doExecute(parameterSource);
}
 
源代码24 项目: spring-analysis-note   文件: SimpleJdbcInsert.java
@Override
public int[] executeBatch(SqlParameterSource... batch) {
	return doExecuteBatch(batch);
}
 
源代码25 项目: SimpleFlatMapper   文件: SqlParameterSourceTest.java
private void validate(SqlParameterSource[] sqlParameterSources) {
    for(int i = 0; i < sqlParameterSources.length; i++) {
        assertEquals((long)i, sqlParameterSources[i].getValue("id"));
    }
}
 
源代码26 项目: SimpleFlatMapper   文件: SqlParameterSourceTest.java
@Test
public void testInstantShouldBeTimestampType() {
    String sql = "INSERT INTO table VALUES(:instant)";

    SqlParameterSourceFactory<ObjectWithInstant> sqlParameters =
            JdbcTemplateMapperFactory
                    .newInstance()
                    .newSqlParameterSourceFactory(ObjectWithInstant.class, sql);

    
    ObjectWithInstant data = new ObjectWithInstant(Instant.now());
    
    SqlParameterSource parameterSource = sqlParameters.newSqlParameterSource(data);

    assertEquals(Types.TIMESTAMP, parameterSource.getSqlType("instant"));
    assertEquals(new Timestamp(data.instant.toEpochMilli()), parameterSource.getValue("instant"));

}
 
源代码27 项目: effectivejava   文件: SimpleJdbcInsert.java
@Override
public KeyHolder executeAndReturnKeyHolder(SqlParameterSource parameterSource) {
	return doExecuteAndReturnKeyHolder(parameterSource);
}
 
源代码28 项目: effectivejava   文件: SimpleJdbcTemplate.java
@Override
public <T> List<T> query(String sql, RowMapper<T> rm, SqlParameterSource args)
		throws DataAccessException {
	return getNamedParameterJdbcOperations().query(sql, args, rm);
}
 
源代码29 项目: effectivejava   文件: CallMetaDataContext.java
/**
 * Match input parameter values with the parameters declared to be used in the call.
 * @param parameterSource the input values
 * @return a Map containing the matched parameter names with the value taken from the input
 */
public Map<String, Object> matchInParameterValuesWithCallParameters(SqlParameterSource parameterSource) {
	// For parameter source lookups we need to provide case-insensitive lookup support
	// since the database metadata is not necessarily providing case sensitive parameter names.
	Map<String, String> caseInsensitiveParameterNames =
			SqlParameterSourceUtils.extractCaseInsensitiveParameterNames(parameterSource);

	Map<String, String> callParameterNames = new HashMap<String, String>(this.callParameters.size());
	Map<String, Object> matchedParameters = new HashMap<String, Object>(this.callParameters.size());
	for (SqlParameter parameter : this.callParameters) {
		if (parameter.isInputValueProvided()) {
			String parameterName = parameter.getName();
			String parameterNameToMatch = this.metaDataProvider.parameterNameToUse(parameterName);
			if (parameterNameToMatch != null) {
				callParameterNames.put(parameterNameToMatch.toLowerCase(), parameterName);
			}
			if (parameterName != null) {
				if (parameterSource.hasValue(parameterName)) {
					matchedParameters.put(parameterName, SqlParameterSourceUtils.getTypedValue(parameterSource, parameterName));
				}
				else {
					String lowerCaseName = parameterName.toLowerCase();
					if (parameterSource.hasValue(lowerCaseName)) {
						matchedParameters.put(parameterName, SqlParameterSourceUtils.getTypedValue(parameterSource, lowerCaseName));
					}
					else {
						String englishLowerCaseName = parameterName.toLowerCase(Locale.ENGLISH);
						if (parameterSource.hasValue(englishLowerCaseName)) {
							matchedParameters.put(parameterName, SqlParameterSourceUtils.getTypedValue(parameterSource, englishLowerCaseName));
						}
						else {
							String propertyName = JdbcUtils.convertUnderscoreNameToPropertyName(parameterName);
							if (parameterSource.hasValue(propertyName)) {
								matchedParameters.put(parameterName, SqlParameterSourceUtils.getTypedValue(parameterSource, propertyName));
							}
							else {
								if (caseInsensitiveParameterNames.containsKey(lowerCaseName)) {
									String sourceName = caseInsensitiveParameterNames.get(lowerCaseName);
									matchedParameters.put(parameterName, SqlParameterSourceUtils.getTypedValue(parameterSource, sourceName));
								}
								else {
									logger.warn("Unable to locate the corresponding parameter value for '" + parameterName +
											"' within the parameter values provided: " + caseInsensitiveParameterNames.values());
								}
							}
						}
					}
				}
			}
		}
	}

	if (logger.isDebugEnabled()) {
		logger.debug("Matching " + caseInsensitiveParameterNames.values() + " with " + callParameterNames.values());
		logger.debug("Found match for " + matchedParameters.keySet());
	}
	return matchedParameters;
}
 
源代码30 项目: java-technology-stack   文件: SimpleJdbcCall.java
@Override
public Map<String, Object> execute(SqlParameterSource parameterSource) {
	return doExecute(parameterSource);
}