Example usage for org.springframework.jdbc.core.namedparam MapSqlParameterSource addValue

List of usage examples for org.springframework.jdbc.core.namedparam MapSqlParameterSource addValue

Introduction

In this page you can find the example usage for org.springframework.jdbc.core.namedparam MapSqlParameterSource addValue.

Prototype

public MapSqlParameterSource addValue(String paramName, @Nullable Object value) 

Source Link

Document

Add a parameter to this parameter source.

Usage

From source file:com.joliciel.lefff.LefffDaoImpl.java

public void deleteAttribute(int attributeId) {
    NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(this.getDataSource());
    MapSqlParameterSource paramSource = new MapSqlParameterSource();
    String sql = "DELETE FROM lef_attribute WHERE attribute_id = :attribute_id";
    paramSource.addValue("attribute_id", attributeId);
    LOG.info(sql);//from ww w  .  j a  v a  2s.  c  o m
    LefffDaoImpl.LogParameters(paramSource);
    jt.update(sql, paramSource);
}

From source file:com.joliciel.lefff.LefffDaoImpl.java

public void deletePredicate(int predicateId) {
    NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(this.getDataSource());
    MapSqlParameterSource paramSource = new MapSqlParameterSource();
    String sql = "DELETE FROM lef_predicate WHERE predicate_id = :predicate_id";
    paramSource.addValue("predicate_id", predicateId);
    LOG.info(sql);// w  w w .j  a  va  2  s. c o  m
    LefffDaoImpl.LogParameters(paramSource);
    jt.update(sql, paramSource);
}

From source file:com.siblinks.ws.service.impl.VideoSubscriptionsServiceImpl.java

/**
 * {@inheritDoc}/*  ww w .j  av  a  2 s . c  o m*/
 */
@Override
@RequestMapping(value = "/getListVideoSubscription", method = RequestMethod.GET)
public ResponseEntity<Response> getListVideoSubscription(@RequestParam("userId") final String userId,
        @RequestParam("subjectId") final String subjectId) {
    SimpleResponse response = null;
    try {
        String method = "getListVideoSubscription()";
        logger.debug(method + " start");

        String entityName = null;
        List<Object> readObject = null;
        String currentDate = "";
        String firstDayOfCurrentWeek = "";
        Object[] queryParams = null;
        Map<String, List<Object>> mapListVideo = new HashMap<String, List<Object>>();

        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            cal.setFirstDayOfWeek(Calendar.MONDAY);
            cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
            Date firstDayOfTheWeek = cal.getTime();

            currentDate = DateUtil.date2YYYYMMDD000000(new Date());
            firstDayOfCurrentWeek = DateUtil.date2YYYYMMDD000000(firstDayOfTheWeek);

            if ("-2".equals(subjectId)) {
                entityName = SibConstants.SqlMapper.SQL_SIB_GET_ALL_VIDEO_SUBSCRIPTION;
                queryParams = new Object[] { userId, currentDate, userId, firstDayOfCurrentWeek, currentDate,
                        userId, firstDayOfCurrentWeek };
                readObject = dao.readObjects(entityName, queryParams);
            } else {
                // Get child category by subjectId
                List<Map<String, Object>> readObjectNoCondition = dao
                        .readObjectNoCondition(SibConstants.SqlMapper.SQL_GET_ALL_CATEGORY_TOPIC);

                MapSqlParameterSource params = new MapSqlParameterSource();

                String allChildCategory = CommonUtil.getAllChildCategory(subjectId, readObjectNoCondition);
                if (!StringUtil.isNull(allChildCategory)) {
                    List<Integer> listChildCategory = new ArrayList<Integer>();
                    String[] arrChildCategory = allChildCategory.split(",");
                    for (String string : arrChildCategory) {
                        listChildCategory.add(Integer.parseInt(string));
                    }
                    params.addValue("subjectID", listChildCategory);

                }
                params.addValue("userID", userId);
                params.addValue("currentDate", currentDate);
                params.addValue("firstDayOfCurrentWeek", firstDayOfCurrentWeek);

                entityName = SibConstants.SqlMapper.SQL_SIB_GET_ALL_VIDEO_SUBSCRIPTION_BY_CATEGORY;

                readObject = dao.readObjectNamedParameter(entityName, params);
            }

            if (readObject == null) {
                readObject = new ArrayList<Object>();
            }

            JSONArray jsonAraay = new JSONArray(readObject);

            for (int i = 0; i < jsonAraay.length(); i++) {
                JSONObject jsonObj = jsonAraay.getJSONObject(i);
                ObjectMapper mapper = new ObjectMapper();
                Object obj = mapper.readValue(jsonObj.toString(), Object.class);
                addMapVideo(mapListVideo, jsonObj.get("flag").toString(), obj);
            }

        } catch (ParseException | IOException e) {
            logger.error(method + " - error : " + e.getMessage());
        }

        response = new SimpleResponse("true", mapListVideo);
    } catch (Exception e) {
        e.printStackTrace();
        response = new SimpleResponse(SibConstants.FAILURE, "video", "getListVideoSubscription",
                e.getMessage());
    }
    return new ResponseEntity<Response>(response, HttpStatus.OK);
}

From source file:alfio.manager.system.DataMigrator.java

void fillReservationsLanguage() {
    transactionTemplate.execute(s -> {
        jdbc.queryForList("select id from tickets_reservation where user_language is null",
                new EmptySqlParameterSource(), String.class).forEach(id -> {
                    MapSqlParameterSource param = new MapSqlParameterSource("reservationId", id);
                    String language = optionally(() -> jdbc.queryForObject(
                            "select user_language from ticket where tickets_reservation_id = :reservationId limit 1",
                            param, String.class)).orElse("en");
                    jdbc.update(//ww  w. j a v a 2s  .  c  o  m
                            "update tickets_reservation set user_language = :userLanguage where id = :reservationId",
                            param.addValue("userLanguage", language));
                });
        return null;
    });
}

From source file:gov.nih.nci.ncicb.tcga.dcc.dam.dao.DAMQueriesLevel2.java

/**
 * Return a {@link List} of {@link DataFile} associated with the given {@link DataSet}s.
 *
 * Note: it is assumed that those {@link DataSet}s are all for 1 single disease type.
 *
 * @param selectedDataSets the {@link DataSet}s
 * @param consolidateFiles whether data for selected data sets should be consolidated into as few files as possible
 * or put in one file per sample//from   w w  w.  ja  v a2 s .co  m
 * @return a {@link List} of {@link DataFile} associated with the given {@link DataSet}s
 * @throws DAMQueriesException
 */
private List<DataFile> getFileInfoForSelectedDataSetsUniqueDisease(final List<DataSet> selectedDataSets,
        final boolean consolidateFiles) throws DAMQueriesException {

    final List<DataFile> dataFiles = new ArrayList<DataFile>();

    final Map<String, DataSetLevelTwoThree> barcodeDataSetMap = getBarcodesForDataSets(selectedDataSets);

    final Set<String> platformIds = new HashSet<String>();
    for (DataSet dataSet : selectedDataSets) {
        if (dataSet.getPlatformId() != null && !StringUtils.isEmpty(dataSet.getPlatformId())) {
            platformIds.add(dataSet.getPlatformId());
        }
    }

    if (barcodeDataSetMap.size() > 0) {
        final List<String> barcodes = new ArrayList(barcodeDataSetMap.keySet());

        transactionTemplate.execute(new TransactionCallback() {
            public Object doInTransaction(final TransactionStatus transactionStatus) {
                // insert barcodes into temp table
                insertBarcodesInToTmpTable(barcodes);
                final ParameterizedRowMapper<DataFile> mapper = new ParameterizedRowMapper<DataFile>() {
                    public DataFile mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                        final DataSet dataSet = barcodeDataSetMap.get(rs.getString(5));
                        final DataFile dataFile = new DataFileLevelTwo();
                        dataFile.setFileId(rs.getString(1));
                        dataFile.setFileName(rs.getString(2));
                        dataFile.setSize(rs.getLong(3));
                        dataFile.setPath(rs.getString(4));
                        dataFile.setPlatformTypeId(dataSet.getPlatformTypeId());
                        dataFile.setCenterId(dataSet.getCenterId());
                        dataFile.setPlatformId(dataSet.getPlatformId());
                        dataFile.setDisplaySample(dataSet.getSample());
                        dataFile.setProtected(dataSet.isProtected());
                        dataFile.setBarcodes(dataSet.getBarcodes());
                        dataFile.setPermanentFile(true);
                        dataFile.setDiseaseType(dataSet.getDiseaseType());
                        return dataFile;
                    }
                };
                // get data files
                final MapSqlParameterSource parameter = new MapSqlParameterSource();
                parameter.addValue("platformids", platformIds);
                final SimpleJdbcTemplate jdbc = new SimpleJdbcTemplate(getDataSource());
                dataFiles.addAll(jdbc.query(FILE_INFO_QUERY, mapper, parameter));
                return null;
            }
        });

        if (consolidateFiles) {

            return buildConsolidatedFiles(dataFiles, barcodeDataSetMap.get(barcodes.get(0)));
        }
    }
    return dataFiles;
}

From source file:com.joliciel.jochre.graphics.GraphicsDaoJdbc.java

@Override
public void deleteContiguousShapeInternal(ShapeInternal shape) {
    NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(this.getDataSource());
    MapSqlParameterSource paramSource = new MapSqlParameterSource();
    paramSource.addValue("shape_id", shape.getId());

    String sql = "DELETE FROM ocr_shape WHERE shape_id = :shape_id";
    LOG.debug(sql);//from  w  w  w  .j a  v  a2 s.  c  o m
    logParameters(paramSource);
    jt.update(sql, paramSource);
}

From source file:com.ushahidi.swiftriver.core.api.dao.impl.JpaDropDao.java

/**
 * Populates the buckets_droplets table/* w  w  w . ja  v  a2 s  . co  m*/
 * 
 * @param drops
 */
private void insertBucketDrops(final List<Drop> drops) {
    // Stores the drop id against the destination bucket ids
    Map<Long, Set<Long>> dropBucketsMap = new HashMap<Long, Set<Long>>();

    // Stores the drop id against its index in the drops list
    final Map<Long, Integer> dropsIndex = new HashMap<Long, Integer>();
    int i = 0;
    for (Drop drop : drops) {
        if (drop.getBucketIds() == null)
            continue;

        Set<Long> bucketSet = new HashSet<Long>();
        bucketSet.addAll(drop.getBucketIds());
        dropBucketsMap.put(drop.getId(), bucketSet);
        dropsIndex.put(drop.getId(), i);
        i++;
    }

    if (dropsIndex.isEmpty())
        return;

    // Exclude existing drops
    String existsSQL = "SELECT `bucket_id`, `droplet_id` "
            + "FROM `buckets_droplets` WHERE `droplet_id` IN (:ids)";

    MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue("ids", dropsIndex.keySet());

    for (Map<String, Object> row : namedJdbcTemplate.queryForList(existsSQL, params)) {
        Long dropId = ((Number) row.get("droplet_id")).longValue();
        Long bucketId = ((Number) row.get("bucket_id")).longValue();

        if (dropBucketsMap.containsKey(dropId)) {
            Set<Long> bucketIdSet = dropBucketsMap.get(dropId);
            bucketIdSet.remove(bucketId);
        }
    }

    // List of arrays comprised of the drop id and bucket id
    final List<Long[]> bucketDropList = new ArrayList<Long[]>();
    for (Map.Entry<Long, Set<Long>> entry : dropBucketsMap.entrySet()) {
        for (Long bucketId : entry.getValue()) {
            Long[] bucketDrop = { bucketId, entry.getKey() };
            bucketDropList.add(bucketDrop);
        }
    }

    if (bucketDropList.isEmpty())
        return;

    // Store for the no. of drops inserted per bucket
    final Map<Long, Integer> bucketDropCount = new HashMap<Long, Integer>();

    // Query for populating TABLE buckets_droplets
    String insertSQL = "INSERT INTO `buckets_droplets` (`bucket_id`, `droplet_id`, `droplet_date_added`) "
            + "VALUES (?, ?, ?)";

    jdbcTemplate.batchUpdate(insertSQL, new BatchPreparedStatementSetter() {
        public void setValues(PreparedStatement ps, int index) throws SQLException {
            Long[] bucketDrop = bucketDropList.get(index);
            Long bucketId = bucketDrop[0];

            ps.setLong(1, bucketId);
            ps.setLong(2, bucketDrop[1]);
            ps.setTimestamp(3, new java.sql.Timestamp(new Date().getTime()));

            Integer count = bucketDropCount.remove(bucketId);
            count = (count == null) ? 1 : new Integer(count.intValue() + 1);
            bucketDropCount.put(bucketId, count);
        }

        @Override
        public int getBatchSize() {
            return bucketDropList.size();
        }
    });

    // Update the drop count for the updated buckets
    final List<Entry<Long, Integer>> bucketDropCountList = new ArrayList<Map.Entry<Long, Integer>>();
    bucketDropCountList.addAll(bucketDropCount.entrySet());

    String updateSQL = "UPDATE `buckets` SET `drop_count` = `drop_count` + ? WHERE `id` = ?";
    jdbcTemplate.batchUpdate(updateSQL, new BatchPreparedStatementSetter() {

        public void setValues(PreparedStatement ps, int i) throws SQLException {
            Entry<Long, Integer> entry = bucketDropCountList.get(i);
            ps.setLong(1, entry.getValue());
            ps.setLong(2, entry.getKey());
        }

        public int getBatchSize() {
            return bucketDropCountList.size();
        }
    });

}

From source file:com.joliciel.jochre.graphics.GraphicsDaoJdbc.java

@Override
public List<Shape> findShapes(GroupOfShapes group) {
    NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(this.getDataSource());
    String sql = "SELECT " + SELECT_SHAPE + " FROM ocr_shape WHERE shape_group_id=:shape_group_id"
            + " ORDER BY shape_index";
    MapSqlParameterSource paramSource = new MapSqlParameterSource();
    paramSource.addValue("shape_group_id", group.getId());

    LOG.debug(sql);/*from   w  w  w  .j  a v  a2 s. c om*/
    logParameters(paramSource);
    @SuppressWarnings("unchecked")
    List<Shape> shapes = jt.query(sql, paramSource, new ShapeMapper(this.getGraphicsServiceInternal()));

    return shapes;
}

From source file:com.joliciel.jochre.graphics.GraphicsDaoJdbc.java

public List<JochreImage> findImages(JochrePage jochrePage) {
    NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(this.getDataSource());
    String sql = "SELECT " + SELECT_IMAGE + " FROM ocr_image WHERE image_page_id=:image_page_id"
            + " ORDER BY image_index";
    MapSqlParameterSource paramSource = new MapSqlParameterSource();
    paramSource.addValue("image_page_id", jochrePage.getId());

    LOG.debug(sql);//from   ww  w. jav a  2s  .  c  o  m
    logParameters(paramSource);
    @SuppressWarnings("unchecked")
    List<JochreImage> images = jt.query(sql, paramSource,
            new JochreImageMapper(this.getGraphicsServiceInternal()));

    return images;
}

From source file:com.joliciel.jochre.graphics.GraphicsDaoJdbc.java

public List<RowOfShapes> findRows(Paragraph paragraph) {
    NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(this.getDataSource());
    String sql = "SELECT " + SELECT_ROW + " FROM ocr_row WHERE row_paragraph_id=:row_paragraph_id"
            + " ORDER BY row_index";
    MapSqlParameterSource paramSource = new MapSqlParameterSource();
    paramSource.addValue("row_paragraph_id", paragraph.getId());

    LOG.debug(sql);/*  w  w  w .j  a v a  2  s. c  o m*/
    logParameters(paramSource);
    @SuppressWarnings("unchecked")
    List<RowOfShapes> rows = jt.query(sql, paramSource,
            new RowOfShapesMapper(this.getGraphicsServiceInternal()));

    return rows;
}