Search in sources :

Example 46 with MapSqlParameterSource

use of org.springframework.jdbc.core.namedparam.MapSqlParameterSource in project Gargoyle by callakrsos.

the class SimpleSQLResultView method executeSQL.

public void executeSQL(Node root) {
    LOGGER.debug("sql check....");
    if (this.sql == null || this.sql.isEmpty()) {
        return;
    }
    LOGGER.debug("param bind....");
    /* [시작] 바인드변수 맵핑시키는 테이블 */
    param.keySet().stream().forEach(key -> {
        KeyValue keyValue = new KeyValue();
        keyValue.setKey(key);
        keyValue.setValue(param.get(key));
        tbBind.getItems().add(keyValue);
    });
    /* [끝] 바인드변수 맵핑시키는 테이블 */
    String wrapperedSQL = ConfigResourceLoader.getInstance().get(ConfigResourceLoader.SQL_LIMIT_WRAPPER);
    LOGGER.debug(String.format("wrapperedSql : %s", wrapperedSQL));
    param.put(ConfigResourceLoader.USER_SQL, this.sql);
    String velocityToText = ValueUtil.getVelocityToText(wrapperedSQL, param);
    param.remove(ConfigResourceLoader.USER_SQL);
    LOGGER.debug(String.format("before velocityText %s", velocityToText));
    String sql = ValueUtil.getVelocityToText(velocityToText, param);
    LOGGER.debug(String.format("after velocityText %s", sql));
    columns = new ArrayList<>();
    try {
        // Iterator<Entry<String, Object>> iterator =
        // param.entrySet().iterator();
        MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource(param);
        // while (iterator.hasNext()) {
        // Entry<String, Object> next = iterator.next();
        // Object value = null;
        // if (next.getValue() != null)
        // value = "'".concat(next.getValue().toString()).concat("'");
        // mapSqlParameterSource.addValue(next.getKey(), value);
        // }
        List<Map<String, Object>> select = DbUtil.select(sql, mapSqlParameterSource, (rs, row) -> {
            Map<String, Object> hashMap = new HashMap<String, Object>();
            final ResultSetMetaData metaData = rs.getMetaData();
            final int columnCount = metaData.getColumnCount();
            hashMap = new HashMap<String, Object>();
            for (int c = 1; c <= columnCount; c++) {
                String columnLabel = metaData.getColumnLabel(c);
                if (row == 0) {
                    TableModelDVO tableModelDVO = new TableModelDVO();
                    tableModelDVO.setDatabaseColumnName(columnLabel);
                    String columnTypeName = metaData.getColumnTypeName(c);
                    if ("unknown".equals(columnTypeName)) {
                        LOGGER.debug("unknown type detected....");
                        LOGGER.debug("convert varchar type...");
                        LOGGER.debug("type Number : " + metaData.getColumnType(c));
                        // TODO 잠재적인 버그가 있을 가능성이 있을지 ???? 확신이 안섬.
                        columnTypeName = "varchar";
                    }
                    tableModelDVO.setDabaseTypeName(columnTypeName);
                    columns.add(tableModelDVO);
                }
                hashMap.put(columnLabel, rs.getString(c));
            }
            return hashMap;
        });
        if (select != null && !select.isEmpty()) {
            clear();
            createColumns(columns);
            tbResult.getItems().addAll(select);
        }
    } catch (Exception e) {
        LOGGER.error(ValueUtil.toString(e));
        // DialogUtil.showConfirmDialog();
        // 에러 다이얼로그 수정.
        DialogUtil.showExceptionDailog(SharedMemory.getPrimaryStage(), e);
    }
    Iterator<String> iterator = param.keySet().iterator();
    while (iterator.hasNext()) {
        String key = iterator.next();
        Object value = param.get(key);
        if (value == null || value.toString().isEmpty())
            param.put(key, null);
        else if (value instanceof List) {
            List<Object> items = (List<Object>) value;
            // StringBuffer sb = new StringBuffer();
            // for (Object obj : items) {
            // sb.append(obj).append(",");
            // }
            // if (items != null && !items.isEmpty()) //bug fix. sb가 빈 경우
            // 에러발생.
            // sb.setLength(sb.length() - 1);
            param.put(key, items);
        } else
            param.put(key, value);
    }
    this.mappingedSqlKeywords.setContent(ValueUtil.getVelocityToText(this.sql, param, true));
    this.sqlKeywords.setContent(this.sql);
}
Also used : KeyValue(com.kyj.fx.voeditor.visual.framework.KeyValue) HashMap(java.util.HashMap) TableModelDVO(kyj.Fx.dao.wizard.core.model.vo.TableModelDVO) IOException(java.io.IOException) ResultSetMetaData(java.sql.ResultSetMetaData) MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource) ArrayList(java.util.ArrayList) List(java.util.List) ObservableList(javafx.collections.ObservableList) HashMap(java.util.HashMap) Map(java.util.Map)

Example 47 with MapSqlParameterSource

use of org.springframework.jdbc.core.namedparam.MapSqlParameterSource in project spring-data-jdbc by spring-projects.

the class DefaultDataAccessStrategy method existsById.

@Override
public <T> boolean existsById(Object id, Class<T> domainType) {
    String existsSql = sql(domainType).getExists();
    MapSqlParameterSource parameter = createIdParameterSource(id, domainType);
    return operations.queryForObject(existsSql, parameter, Boolean.class);
}
Also used : MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource)

Example 48 with MapSqlParameterSource

use of org.springframework.jdbc.core.namedparam.MapSqlParameterSource in project spring-data-jdbc by spring-projects.

the class DefaultDataAccessStrategy method findAllById.

@Override
public <T> Iterable<T> findAllById(Iterable<?> ids, Class<T> domainType) {
    String findAllInListSql = sql(domainType).getFindAllInList();
    Class<?> targetType = getRequiredPersistentEntity(domainType).getRequiredIdProperty().getColumnType();
    MapSqlParameterSource parameter = new // 
    MapSqlParameterSource(// 
    "ids", // 
    StreamSupport.stream(ids.spliterator(), false).map(// 
    id -> convert(id, targetType)).collect(// 
    Collectors.toList()));
    return operations.query(findAllInListSql, parameter, getEntityRowMapper(domainType));
}
Also used : MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource)

Example 49 with MapSqlParameterSource

use of org.springframework.jdbc.core.namedparam.MapSqlParameterSource in project spring-data-jdbc by spring-projects.

the class DefaultDataAccessStrategy method getPropertyMap.

private <S> MapSqlParameterSource getPropertyMap(final S instance, JdbcPersistentEntity<S> persistentEntity) {
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    persistentEntity.doWithProperties((PropertyHandler<JdbcPersistentProperty>) property -> {
        if (!property.isEntity()) {
            Object value = persistentEntity.getPropertyAccessor(instance).getProperty(property);
            Object convertedValue = convert(value, property.getColumnType());
            parameters.addValue(property.getColumnName(), convertedValue, JdbcUtil.sqlTypeFor(property.getColumnType()));
        }
    });
    return parameters;
}
Also used : NonTransientDataAccessException(org.springframework.dao.NonTransientDataAccessException) EntityInformation(org.springframework.data.repository.core.EntityInformation) HashMap(java.util.HashMap) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException) JdbcUtil(org.springframework.data.jdbc.support.JdbcUtil) MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource) KeyHolder(org.springframework.jdbc.support.KeyHolder) Collectors(java.util.stream.Collectors) NamedParameterJdbcOperations(org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations) PropertyHandler(org.springframework.data.mapping.PropertyHandler) GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) Map(java.util.Map) BasicJdbcPersistentEntityInformation(org.springframework.data.jdbc.mapping.model.BasicJdbcPersistentEntityInformation) JdbcPersistentEntity(org.springframework.data.jdbc.mapping.model.JdbcPersistentEntity) RowMapper(org.springframework.jdbc.core.RowMapper) Optional(java.util.Optional) StreamSupport(java.util.stream.StreamSupport) JdbcPersistentProperty(org.springframework.data.jdbc.mapping.model.JdbcPersistentProperty) PropertyPath(org.springframework.data.mapping.PropertyPath) JdbcPersistentEntityInformation(org.springframework.data.jdbc.mapping.model.JdbcPersistentEntityInformation) JdbcMappingContext(org.springframework.data.jdbc.mapping.model.JdbcMappingContext) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) Assert(org.springframework.util.Assert) JdbcPersistentProperty(org.springframework.data.jdbc.mapping.model.JdbcPersistentProperty) MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource)

Example 50 with MapSqlParameterSource

use of org.springframework.jdbc.core.namedparam.MapSqlParameterSource in project spring-data-jdbc by spring-projects.

the class JdbcRepositoryQuery method execute.

@Override
public Object execute(Object[] objects) {
    String query = determineQuery();
    MapSqlParameterSource parameters = bindParameters(objects);
    if (queryMethod.isModifyingQuery()) {
        int updatedCount = context.getTemplate().update(query, parameters);
        Class<?> returnedObjectType = queryMethod.getReturnedObjectType();
        return (returnedObjectType == boolean.class || returnedObjectType == Boolean.class) ? updatedCount != 0 : updatedCount;
    }
    if (queryMethod.isCollectionQuery() || queryMethod.isStreamQuery()) {
        return context.getTemplate().query(query, parameters, rowMapper);
    }
    try {
        return context.getTemplate().queryForObject(query, parameters, rowMapper);
    } catch (EmptyResultDataAccessException e) {
        return null;
    }
}
Also used : MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException)

Aggregations

MapSqlParameterSource (org.springframework.jdbc.core.namedparam.MapSqlParameterSource)51 EmptyResultDataAccessException (org.springframework.dao.EmptyResultDataAccessException)20 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)15 Attribute (cz.metacentrum.perun.core.api.Attribute)10 RichAttribute (cz.metacentrum.perun.core.api.RichAttribute)9 ConsistencyErrorRuntimeException (cz.metacentrum.perun.core.api.exceptions.rt.ConsistencyErrorRuntimeException)9 InternalErrorRuntimeException (cz.metacentrum.perun.core.api.exceptions.rt.InternalErrorRuntimeException)9 Test (org.junit.Test)8 ArrayList (java.util.ArrayList)6 SimpleJdbcInsert (org.springframework.jdbc.core.simple.SimpleJdbcInsert)4 Member (cz.metacentrum.perun.core.api.Member)3 HashMap (java.util.HashMap)3 SqlOutParameter (org.springframework.jdbc.core.SqlOutParameter)3 SqlParameter (org.springframework.jdbc.core.SqlParameter)3 ParsedSql (org.springframework.jdbc.core.namedparam.ParsedSql)3 User (cz.metacentrum.perun.core.api.User)2 IOException (java.io.IOException)2 ResultSet (java.sql.ResultSet)2 HashSet (java.util.HashSet)2 Map (java.util.Map)2